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

相关内容

热门资讯

终于发现!兴动互娱辅助脚本io... 终于发现!兴动互娱辅助脚本ios下载,佛手在线修改器(详细辅助解密教程)1、在兴动互娱辅助脚本ios...
透视有挂"拱趴大菠萝... 透视有挂"拱趴大菠萝有什么挂"详细辅助教你教程(往昔存在有挂)1、点击下载安装,微扑克wpk插件透视...
专业讨论!福建大玩家辅助透视,... 专业讨论!福建大玩家辅助透视,小程序游戏辅助必赢(详细辅助2025版教程);无聊就玩这款福建大玩家辅...
透视辅助"wepok... 《透视辅助"wepoker私人局俱乐部怎么进"详细辅助wpk教程(从来是有挂)》 wepoker私人...
重大推荐!多乐辅助器使用教程,... 重大推荐!多乐辅助器使用教程,大菠萝免费辅助器(详细辅助高科技教程)1、很好的工具软件,可以解锁游戏...
揭秘关于!温州茶苑手机版辅助器... 揭秘关于!温州茶苑手机版辅助器,心悦填大坑辅助器下载(详细辅助透牌教程)1、金币登录送、破产送、升级...
透视黑科技"德普之星... 1、透视黑科技"德普之星透视软件免费入口官网"详细辅助可靠教程(总是存在有挂)。2、德普之星透视软件...
让我来分享经验!潮汕掌上娱透视... 让我来分享经验!潮汕掌上娱透视怎么买,哈灵脚本微信小程序(详细辅助2025新版技巧)1、潮汕掌上娱透...
透视模拟器"hhpo... 1、透视模拟器"hhpoker真能买到挂吗"详细辅助高科技教程(果然是真的有挂)。2、hhpoker...
一分钟秒懂!微信小程序打哈儿脚... 一分钟秒懂!微信小程序打哈儿脚本,爱来辅助器(详细辅助科技教程),您好,微信小程序打哈儿脚本这款游戏...