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及更高版本上,将前台服务设置为具

相关内容

热门资讯

最初有开挂"九天大厅... 最初有开挂"九天大厅挂价格"开挂(透视)辅助插件(2026版教程有挂攻略);打开点击测试直接进入微信...
素来有开挂"poke... 【亲,pokemmo手机版修改器 这款游戏可以开挂的,确实是有挂的,很多玩家在这款pokemmo手机...
本来有辅助"789大... 本来有辅助"789大菠萝如何手气顺"开挂(透视)辅助脚本(攻略教程有挂头条)《详细加薇1367043...
从前有开挂"798大... 从前有开挂"798大菠萝辅助"开挂(透视)辅助下载(微扑克教程真的有挂);打开点击测试直接进入微信(...
原先有辅助"心悦ap... 您好:心悦app辅助工具这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
素来有辅助"八闽状元... 您好:这款八闽状元郎破解版辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款八闽状元郎破解版辅助游戏...
本来有辅助"hhpo... 本来有辅助"hhpoker辅助挂是真的吗"开挂(透视)辅助安装(大神讲解有挂透明挂)《详细加薇136...
从前有辅助"途游手游... 从前有辅助"途游手游辅助"开挂(透视)辅助插件(详细教程有挂分享);打开点击测试直接进入微信(136...
原先有辅助"凑一桌关... 原先有辅助"凑一桌关春天怎么开透视"开挂(透视)辅助下载(透视教程竟然有挂);无需打开直接搜索薇:1...
从前有辅助"微信小程... 从前有辅助"微信小程序自动透视免费"开挂(透视)辅助神器(技巧教程有挂透明挂);亲,微信小程序自动透...