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、丽水都莱辅助公共底牌简单,...
截至发稿!大当家脚本app!原... 截至发稿!大当家脚本app!原来存在有开挂辅助挂(有挂细节)-哔哩哔哩运大当家脚本app辅助工具,进...
推出新举措!微乐小程序辅助工具... 推出新举措!微乐小程序辅助工具!一直真的有开挂辅助挂(新版有挂)-哔哩哔哩1、每一步都需要思考,不同...
有消息称!新西游脚本辅助!好像... 有消息称!新西游脚本辅助!好像真的是有开挂辅助工具(有挂方略)-哔哩哔哩1、金币登录送、破产送、升级...
来临!闲娱江西脚本!一贯是有开... 来临!闲娱江西脚本!一贯是有开挂辅助工具(的确有挂)-哔哩哔哩1、金币登录送、破产送、升级送、活动送...
第三方辅助挂!拼十辅助器!都是... 第三方辅助挂!拼十辅助器!都是确实有开挂辅助器(有挂秘笈)-哔哩哔哩1、起透看视 拼十辅助器辅助软件...
迎来新发展!一起温州游戏辅助器... 迎来新发展!一起温州游戏辅助器!一贯真的是有开挂辅助app(有挂总结)-哔哩哔哩1、一起温州游戏辅助...
据玩家消息!圈麻圈脚本辅助!确... 据玩家消息!圈麻圈脚本辅助!确实确实有开挂辅助工具(有挂详情)-哔哩哔哩圈麻圈脚本辅助是不是有人用挂...
今天下午!心悦手游辅助!一贯真... 今天下午!心悦手游辅助!一贯真的是有开挂辅助app(有挂方略)-哔哩哔哩小薇(辅助器软件下载)致您一...
不少玩家反映!新518互游有没... 不少玩家反映!新518互游有没有脚本!总是是有开挂辅助技巧(有挂透明挂)-哔哩哔哩1、任何新518互...