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分钟实锤!智星德州菠萝外挂(... 1分钟实锤!智星德州菠萝外挂(德州)总是真的是有挂(详细辅助AA德州教程);1、任何智星德州菠萝外挂...
2分钟实锤!智星德州菠萝外挂(... 2分钟实锤!智星德州菠萝外挂(来玩德州)竟然是真的有挂(详细辅助技巧教程)1、任何智星德州菠萝外挂a...
第8分钟实锤!智星德州菠萝辅助... 第8分钟实锤!智星德州菠萝辅助器(德州ai)总是真的是有挂(详细辅助介绍教程)1、用户打开应用后不用...
8分钟实锤!德扑之星猫腻(德州... 8分钟实锤!德扑之星猫腻(德州wepower)确实真的是有挂(详细辅助第三方教程)1、德扑之星猫腻系...
第2分钟实锤!智星德州菠萝(线... 第2分钟实锤!智星德州菠萝(线上德州)切实有挂(详细辅助第三方教程)第2分钟实锤!智星德州菠萝(线上...
3分钟实锤!德扑ai助手(nz... 3分钟实锤!德扑ai助手(nzt德州)确实是有挂(详细辅助透明挂教程);1、玩家可以在德扑ai助手软...
第二分钟实锤!德扑之星有猫腻(... 第二分钟实锤!德扑之星有猫腻(德州app)本来真的有挂(详细辅助wpk教程)1、第二分钟实锤!德扑之...
第十分钟实锤!德州之星外挂(德... 第十分钟实锤!德州之星外挂(德州nzt)果然真的有挂(详细辅助AI教程)该软件可以轻松地帮助玩家将德...
第3分钟实锤!智星德州菠萝有挂... 第3分钟实锤!智星德州菠萝有挂吗(nzt德州)其实有挂(详细辅助科技教程)1、点击下载安装,智星德州...
第6分钟实锤!德扑之星有作弊(... 第6分钟实锤!德扑之星有作弊(nzt德州)真是存在有挂(详细辅助黑科技教程)进入游戏-大厅左侧-新手...