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、游戏颠覆性的策略玩法,独创攻略技...
推出新举措!关春天辅助凑一桌,... 推出新举措!关春天辅助凑一桌,确实是真的辅助安装(有挂攻略)-哔哩哔哩1、关春天辅助凑一桌有没有辅助...
今日!斗棋联盟俱乐部辅助挂,其... 今日!斗棋联盟俱乐部辅助挂,其实是真的辅助下载(有挂分析)-哔哩哔哩运斗棋联盟俱乐部辅助挂辅助工具,...
出现新变化!微信小程序雀神广东... 出现新变化!微信小程序雀神广东智能辅助,确实是真的辅助神器(有挂猫腻)-哔哩哔哩1、每一步都需要思考...