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、下载好广发正确养号方法之后点击打开...
分享一款透视挂!微壳跑胡子辅助... 分享一款透视挂!微壳跑胡子辅助透视挂,江南娱乐是有外挂,都是有挂方法1、每一步都需要思考,不同水平的...
一分钟了解开挂!大玩家十三水辅... 一分钟了解开挂!大玩家十三水辅助透视挂,约战大同麻将存在有外挂,确实有挂技术一、大玩家十三水游戏安装...
安装程序教程辅助!全民牛牛辅助... 安装程序教程辅助!全民牛牛辅助透视挂,微乐辽宁麻将是真的有外挂,切实有挂规律1、下载好微乐辽宁麻将正...
科普分享开挂!卡丁互娱辅助透视... 科普分享开挂!卡丁互娱辅助透视挂,亲友汇是真的有外挂,其实有挂神器暗藏猫腻,小编详细说明卡丁互娱破解...
必备辅助推荐透视挂!牛犇互娱辅... 必备辅助推荐透视挂!牛犇互娱辅助透视挂,斗棋红中是有外挂,确实真的有挂1、下载好牛犇互娱脚本下载之后...
事发当天透视挂!情怀娱乐辅助透... 事发当天透视挂!情怀娱乐辅助透视挂,三晋麻将确实有外挂,真是真实有挂暗藏猫腻,小编详细说明情怀娱乐破...
热点推荐透视挂!天乐辅助透视挂... 您好,天乐这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏...
玩家必看分享透视挂!正版授权辅... 玩家必看分享透视挂!正版授权辅助透视挂,上游炸金花真的有外挂,一贯揭秘有挂1.正版授权 选牌创建新账...
玩家攻略透视挂!桃乐永州扯胡子... 玩家攻略透视挂!桃乐永州扯胡子辅助透视挂,龙港麻将是真的有外挂,好像有挂细节1、下载好桃乐永州扯胡子...