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、家乡大二技巧辅助器安...
透视好友!哈糖大菠萝可以开挂吗... 透视好友!哈糖大菠萝可以开挂吗,对战互娱辅助系统,阶段辅助脚本(有挂讲解)-哔哩哔哩哈糖大菠萝可以开...
此事引发网友热议!人人燕赵辅助... 此事引发网友热议!人人燕赵辅助(辅助)确实真的有辅助挂(有挂方略)-哔哩哔哩1、全新机制【人人燕赵辅...
透视好友房!拱趴大菠萝万能挂图... 透视好友房!拱趴大菠萝万能挂图解,中至余干小程序辅助器,手筋辅助插件(有挂秘诀)-哔哩哔哩1、拱趴大...
做出回应!皇豪互众辅助软件是干... 做出回应!皇豪互众辅助软件是干嘛的(辅助)好像有挂辅助插件(有挂规律)-哔哩哔哩1、皇豪互众辅助软件...
据权威媒体报道!werplan... 据权威媒体报道!werplan透视挂,丽水跑得快辅助工具,步骤辅助神器(有人有挂)-哔哩哔哩在进入丽...
据通报!凑一桌游戏作z弊(辅助... 据通报!凑一桌游戏作z弊(辅助)其实存在有辅助神器(有挂猫腻)-哔哩哔哩1、凑一桌游戏作z弊模拟器是...
反观!陕麻全黑科技(辅助)一直... 反观!陕麻全黑科技(辅助)一直是真的辅助工具(竟然有挂)-哔哩哔哩陕麻全黑科技是不是有人用挂微扑克w...