Android10在内存清理时结束前台服务
创始人
2024-08-20 08:30:13
0次

在AndroidManifest.xml中,添加以下代码,使应用程序免受最新更新影响:




在对应的Service类中,添加以下代码,以确保前台服务不会在内存清理时被杀死:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        String channelId = "your_channel_id";
        NotificationChannel channel =
                new NotificationChannel(channelId, "Foreground Service Channel",
                        NotificationManager.IMPORTANCE_HIGH);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                .createNotificationChannel(channel);
        Notification notification = new NotificationCompat.Builder(this, channelId)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .build();

        serviceIntent = intent;
        startForeground(1, notification);
        return START_REDELIVER_INTENT;
    } else {
        return super.onStartCommand(intent, flags, startId);
    }
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());

        PendingIntent restartServicePendingIntent =
                PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent,
                        PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService =
                (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        if (alarmService != null) {
            alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000,
                    restartServicePendingIntent);
        }
        super.onTaskRemoved(rootIntent);
    }
}

以上代码的作用是在Android 10及更高版本上,将前台服务设置为具

相关内容

热门资讯

WPK购买方针!微扑克透视脚本... WPK购买方针!微扑克透视脚本,菠萝智星德州ai多功能辅助神器1)微扑克透视脚本免费钻石:进一步探索...
WPK透视讲义!智星菠萝透视,... WPK透视讲义!智星菠萝透视,德扑之星ai多功能透视挂神器1、全新机制【智星菠萝透视ai辅助工具激活...
WPK德州局指南书!werpl... WPK德州局指南书!werplan怎么作弊,wpkai多功能辅助教程werplan怎么作弊脚本下载中...
WPK工具法子!AApoker... WPK工具法子!AApoker靠谱,智星菠萝德州ai多功能辅助app在进入AApoker靠谱软件靠谱...
WPK控制牌步骤!智星德州插件... WPK控制牌步骤!智星德州插件2024最新版,智星菠萝德州ai多功能辅助app进入游戏-大厅左侧-新...
WPK方法阶段!aapoker... WPK方法阶段!aapoker辅助怎么用,菠萝智星德州ai多功能透视挂软件1、玩家可以在aapoke...
WPK安装技法!微扑克透视脚本... WPK安装技法!微扑克透视脚本,WePoKerai多功能透视app1、用户打开应用后不用登录就可以直...
WPK辅助器指南!德普之星辅助... WPK辅助器指南!德普之星辅助工具如何打开,菠萝智星德州ai多功能透视神器1)德普之星辅助工具如何打...
WPK控制牌教材!we pok... WPK控制牌教材!we poker免费辅助器,AApokerai多功能开挂插件1、点击下载安装,we...
WPK四人机巧!wpk俱乐部是... WPK四人机巧!wpk俱乐部是真的吗,红龙扑克ai多功能透视app1、wpk俱乐部是真的吗透视辅助软...