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

相关内容

热门资讯

2027版开挂!和盛娱乐开挂多... 2027版开挂!和盛娱乐开挂多功能AI攻略,和盛娱乐切实有开挂攻略1、起透看视 和盛娱乐辅助软件价格...
2027版辅助器!乐趣麻将辅助... 2027版辅助器!乐趣麻将辅助器多功能AI技巧,乐趣麻将一贯是真的有辅助器技巧1、上手简单,内置详细...
2027版透视器!闲来贵州麻将... 2027版透视器!闲来贵州麻将透视器多功能AI软件,闲来贵州麻将都是有透视器软件1、闲来贵州麻将破解...
2027版外挂!上楚湖北麻将外... 2027版外挂!上楚湖北麻将外挂多功能AI脚本,上楚湖北麻将好像是有外挂脚本1、全新机制【上楚湖北麻...
2027版开挂!超级马里奥开挂... 2027版开挂!超级马里奥开挂多功能AI脚本,超级马里奥一直真的是有开挂脚本超级马里奥脚本下载中分为...
2027版透视器!中至江西麻将... 2027版透视器!中至江西麻将透视器多功能AIapp,中至江西麻将果然是有透视器app一、中至江西麻...
2027版辅助!非常竞技辅助多... 2027版辅助!非常竞技辅助多功能AI攻略,非常竞技总是真的有辅助攻略暗藏猫腻,小编详细说明非常竞技...
2027版开挂!吉祥休闲开挂多... 2027版开挂!吉祥休闲开挂多功能AI教程,吉祥休闲都是是真的有开挂教程1、玩家可以在吉祥休闲透视最...
2027版作弊器!南通长牌作弊... 2027版作弊器!南通长牌作弊器多功能AI攻略,南通长牌切实是有作弊器攻略1、首先打开南通长牌辅助器...
2027版透视挂!心悦填大坑透... 2027版透视挂!心悦填大坑透视挂多功能AI软件,心悦填大坑总是有透视挂软件一、心悦填大坑游戏安装教...