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

相关内容

热门资讯

八分钟辅助!aapoker破解... 八分钟辅助!aapoker破解侠是真的吗,aapoker怎么设置提高好牌几率,窍门教程(有挂透视)1...
第五分钟辅助!wepoker数... 第五分钟辅助!wepoker数据分析,wpk有那种辅助吗,练习教程(有挂细节)1、玩家可以在wpk有...
4分钟辅助!hhpoker辅助... 4分钟辅助!hhpoker辅助挂下载,hhpoker德州牛仔视频,诀窍教程(有挂神器)1、hhpok...
第3分钟辅助!wepoker祈... 第3分钟辅助!wepoker祈福有用吗,pokeplus脚本,绝活儿教程(真的有挂)1、起透看视 w...
第六分钟辅助!werplan脚... 第六分钟辅助!werplan脚本,aapoker怎么控制牌,技法教程(真的有挂)aapoker怎么控...
第六分钟辅助!德普之星怎么开辅... 第六分钟辅助!德普之星怎么开辅助,德州局脚本,讲义教程(有挂教学)亲,关键说明,德普之星怎么开辅助透...
一分钟辅助!hhpoker是真... 一分钟辅助!hhpoker是真的还是假的,红龙poker辅助平台,方式教程(有挂秘籍)1、hhpok...
第三分钟辅助!哈糖大菠萝万能挂... 第三分钟辅助!哈糖大菠萝万能挂,hhpoker的辅助是真的吗,资料教程(有挂方式)1、hhpoker...
6分钟辅助!wepoker透视... 6分钟辅助!wepoker透视有没有,wepokerplus万能挂,步骤教程(真的有挂)一、wepo...
第8分钟辅助!wepoker辅... 第8分钟辅助!wepoker辅助器是真的吗,wepoker透视脚本免费app,指引教程(真是有挂)1...