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

相关内容

热门资讯

4分钟脚本!福建大玩家透视,雀... 4分钟脚本!福建大玩家透视,雀友会广东潮汕苹果(本来真的是有辅助工具)-哔哩哔哩;1、雀友会广东潮汕...
6分钟安装!大菠萝挂机辅助,四... 6分钟安装!大菠萝挂机辅助,四川家园辅助器(都是真的有辅助平台)-哔哩哔哩1、玩家可以在四川家园辅助...
第六分钟插件!欢乐情怀脚本辅助... 第六分钟插件!欢乐情怀脚本辅助器,奇迹陕西游戏辅助器(果然真的有辅助插件)-哔哩哔哩进入游戏-大厅左...
第七分钟安装!新超圣伏虎,开心... 第七分钟安装!新超圣伏虎,开心泉州小程序辅助哪里查看(原来真的有辅助工具)-哔哩哔哩1、用户打开应用...
5分钟安装!巴郎新疆辅助器,情... 5分钟安装!巴郎新疆辅助器,情怀宜春怎么开挂(一贯真的有辅助平台)-哔哩哔哩1、情怀宜春怎么开挂脚本...
八分钟插件!新永和源代码,钱塘... 八分钟插件!新永和源代码,钱塘十水三攻略(好像有挂辅助平台)-哔哩哔哩1、钱塘十水三攻略辅助器安装包...
十分钟辅助!yy比鸡脚本,越乡... 十分钟辅助!yy比鸡脚本,越乡游辅助工具(确实是有辅助神器)-哔哩哔哩所有人都在同一条线上,像星星一...
九分钟安装!789大菠萝可以控... 九分钟安装!789大菠萝可以控制吗,拱趴大菠萝技巧(竟然存在有辅助下载)-哔哩哔哩一、789大菠萝可...
三分钟阶段!wepoker一直... 三分钟阶段!wepoker一直输的号能继续打吗(透视)一直是真的有辅助开挂(哔哩哔哩)1、wepok...
8分钟辅助!扣点点脚本辅助器,... 8分钟辅助!扣点点脚本辅助器,蛮籽酉阳大贰辅助(一直是有辅助软件)-哔哩哔哩小薇(辅助器软件下载)致...