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

相关内容

热门资讯

我来教大家!佛手在线是不是有挂... 我来教大家!佛手在线是不是有挂,德州辅助工具到底怎么样,一贯真的是有挂(有挂攻略)1、点击下载安装,...
新手必备!哈糖大菠萝软件下载,... 新手必备!哈糖大菠萝软件下载,we poker游戏下,总是存在有挂(今日头条)1、脚本辅助下载、免费...
终于清楚!wepoker游戏的... 终于清楚!wepoker游戏的安装教程,wpk私人局有透视吗,本来有挂(有挂秘籍)1)辅助插件:进一...
科技通报!红龙poker辅助,... 科技通报!红龙poker辅助,pokemmo脚本辅助下载,原来是真的有挂(有挂详情)该软件可以轻松地...
总算明白!hhpoker作弊实... 总算明白!hhpoker作弊实战视频,wpk德州局透视,竟然存在有挂(有挂规律)1、完成有辅助插件,...
玩家必看科普!aa poker... 玩家必看科普!aa poker辅助,aapoker插件下载,果然真的是有挂(存在有挂)1、公共底牌简...
今日头条!wepoker辅助器... 今日头条!wepoker辅助器安装包定制,aapoker怎么开辅助器,切实是真的有挂(有挂攻略)1、...
总算了解!werplan怎么作... 总算了解!werplan怎么作弊,wepoker破解是真的还是假的,都是是真的有挂(有挂总结)1、模...
如何分辨真伪!pokemmo脚... 如何分辨真伪!pokemmo脚本辅助器下载,智星菠萝辅助,总是真的是有挂(发现有挂)1、任何透视是真...
查到实测辅助!wepoker有... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...