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

相关内容

热门资讯

第5分钟辅助挂!大唐辅助器免费... 一、光明大厅微信链接辅助试用简介了解软件请加微:136704302光明大厅微信链接辅助试用是一款在线...
两分钟辅助挂!微乐自建房辅助(... 两分钟辅助挂!微乐自建房辅助(透视)对战互娱有辅助吗(详细透视外开挂教程)1)对战互娱有辅助吗辅助挂...
第四分钟辅助挂!陕麻圈插件注入... 第四分钟辅助挂!陕麻圈插件注入(透视)四川家园辅助器(详细透视外开挂教程)1、让任何用户在无需四川家...
五分钟辅助挂!禅游科技辅助(透... 五分钟辅助挂!禅游科技辅助(透视)中至余干破解器(详细透视外开挂教程)1、在中至余干破解器ai机器人...
第八分钟辅助挂!福建天天开心万... 自定义福建天天开心万能辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,...
第9分钟辅助挂!广东雀神智能插... 第9分钟辅助挂!广东雀神智能插件试用(透视)新玄龙辅助(详细透视外开挂教程)1、用户打开应用后不用登...
第五分钟辅助挂!贰柒拾手机辅助... 一、创思维辅助软件简介了解软件请加微:136704302创思维辅助软件是一款在线扑克游戏平台,玩家可...
第五分钟辅助挂!吉祥填大坑有插... 第五分钟辅助挂!吉祥填大坑有插件吗(透视)宝宝吃吃吃游戏辅助(详细透视外开挂教程)1、完成吉祥填大坑...
7分钟辅助挂!越乡游义乌微信小... 7分钟辅助挂!越乡游义乌微信小程序(透视)浙江宝宝游戏辅助器是真的嘛(详细透视外开挂教程)1、每一步...
第七分钟辅助挂!山西打锅子技巧... 第七分钟辅助挂!山西打锅子技巧(透视)广西友乐软件辅助(详细透视外开挂教程)是一款可以让一直输的玩家...