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、多乐辅助器使用教程...
第2分钟了解!川南久久辅助!确... 第2分钟了解!川南久久辅助!确实存在有辅助教程(竟然有挂)-哔哩哔哩1、川南久久辅助辅助软件下载优化...
第3分钟了解!jj斗地主麻将外... 您好,jj斗地主麻将外g挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
第九分钟了解!多乐跑的快脚本!... 第九分钟了解!多乐跑的快脚本!总是存在有辅助工具(有挂辅助)-哔哩哔哩1、多乐跑的快脚本公共底牌简单...
三分钟了解!蜀山四川怎么提高胜... 三分钟了解!蜀山四川怎么提高胜率!好像一直都是有辅助教程(有挂神器)-哔哩哔哩1、每一步都需要思考,...
2分钟了解!新518互游脚本!... 2分钟了解!新518互游脚本!切实存在有辅助教程(有挂辅助)-哔哩哔哩1、不需要AI权限,帮助你快速...
第2分钟了解!打罗松必胜技巧!... 第2分钟了解!打罗松必胜技巧!一直是有辅助技巧(有挂教学)-哔哩哔哩一、打罗松必胜技巧可以开透视的定...
6分钟了解!约战青山晃晃辅助器... 6分钟了解!约战青山晃晃辅助器!本来存在有辅助插件(有挂细节)-哔哩哔哩1、用户打开应用后不用登录就...
八分钟了解!九天大厅辅助器!原... 八分钟了解!九天大厅辅助器!原来一直都是有辅助软件(有挂细节)-哔哩哔哩小薇(辅助器软件下载)致您一...