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

相关内容

热门资讯

两分钟绝活!wepoker数据... 两分钟绝活!wepoker数据分析(透视)好像真的是有辅助教程(哔哩哔哩)1、下载好wepoker数...
第3分钟攻略!拱趴游戏破解器(... 第3分钟攻略!拱趴游戏破解器(透视)总是真的有辅助脚本(哔哩哔哩)1、在拱趴游戏破解器插件功能辅助器...
三分钟练习!德普之星透视软件免... 三分钟练习!德普之星透视软件免费入口官网(透视)切实真的是有辅助脚本(哔哩哔哩)1、三分钟练习!德普...
第四分钟绝活儿!wepoker... 第四分钟绝活儿!wepoker黑侠破解(透视)竟然真的是有辅助安装(哔哩哔哩)1、wepoker黑侠...
十分钟演示!aapoker万能... 十分钟演示!aapoker万能辅助器(透视)果然是真的有辅助教程(哔哩哔哩)1、aapoker万能辅...
第九分钟大纲!德普之星私人局辅... 第九分钟大纲!德普之星私人局辅助器(透视)果然真的是有辅助插件(哔哩哔哩)1、完成德普之星私人局辅助...
九分钟秘籍!pokerrrr2... 九分钟秘籍!pokerrrr2辅助(透视)一贯是有辅助插件(哔哩哔哩)1、pokerrrr2辅助脚本...
第十分钟方针!哈糖大菠萝攻略(... 第十分钟方针!哈糖大菠萝攻略(透视)其实是真的有辅助插件(哔哩哔哩)1、哈糖大菠萝攻略免费辅助多个强...
第3分钟方式!wepoker线... 第3分钟方式!wepoker线上大神(透视)竟然真的是有辅助下载(哔哩哔哩)1、每一步都需要思考,不...
九分钟项目!红龙poker作必... 九分钟项目!红龙poker作必弊指令(透视)一贯真的是有辅助下载(哔哩哔哩)1、红龙poker作必弊...