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.广东雀神智能插件辅...
透视脚本!大菠萝免费辅助&qu... 您好,大菠萝免费辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
透视ai代打!神兽大厅源码&q... 透视ai代打!神兽大厅源码"解密辅助器"本来真的有挂(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激...
记者获悉!微信第三方辅助软件&... 记者获悉!微信第三方辅助软件"关于辅助方法"一直存在有挂(哔哩哔哩)1、许多玩家不知道微信第三方辅助...
明白辅助挂!微信茶馆辅助&qu... 明白辅助挂!微信茶馆辅助"解迷辅助神器"好像确实有挂(哔哩哔哩);1)微信茶馆辅助辅助插件:进一步探...
透视科技!心悦辅助器"... 透视科技!心悦辅助器"解迷辅助教程"确实是有挂(哔哩哔哩)1)心悦辅助器免费钻石:进一步探索心悦辅助...
规律辅助挂!拱趴大菠萝辅助公户... 规律辅助挂!拱趴大菠萝辅助公户"总结辅助脚本"一直是有挂(哔哩哔哩);1、实时拱趴大菠萝辅助公户透视...
连日来!新上游反杀微信辅助&q... 连日来!新上游反杀微信辅助"揭露辅助方法"果然是有挂(哔哩哔哩)1、这是跨平台的新上游反杀微信辅助轻...
2026版教学!中至赣牌圈挂件... 2026版教学!中至赣牌圈挂件多少钱一个"普及辅助方法"总是确实有挂(哔哩哔哩);1、上手简单,内置...
第三方技巧!广东老友辅助&qu... 您好,广东老友辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...