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

相关内容

热门资讯

玩家必备攻略!微乐自建房辅助工... 玩家必备攻略!微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)app1、微乐家乡麻将自...
分享认知!微乐微信自建房辅助工... 分享认知!微乐微信自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)脚本1、每一步都需要思考,...
三分钟了解!微乐自建房辅助工具... 三分钟了解!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)技巧1、微乐自建房辅助工具挂透视...
一分钟快速了解!微乐小程序麻将... 一分钟快速了解!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)教程1、这是跨...
专业讨论!微乐自建房辅助工具神... 专业讨论!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)脚本1、微乐自建房辅助工具神器模...
大家学习交流!微乐家乡麻将自建... 大家学习交流!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)教程1、该软件...
记者揭秘!微信雀神麻将挂件开挂... 记者揭秘!微信雀神麻将挂件开挂辅助,微乐家乡麻将自建房辅助app(开挂自建房)app1、每一步都需要...
我来分享!微乐自建房辅助工具脚... 我来分享!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)脚本1、下载好微乐自建房辅助工...
玩家实测!微乐微信自建房辅助工... 玩家实测!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)软件1、微乐微信自建房辅助工...
终于懂了!微乐自建房辅助工具脚... 终于懂了!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)攻略1.微乐自建房辅助工具脚本...