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

相关内容

热门资讯

推荐一款!随意玩俱乐部辅助,w... 推荐一款!随意玩俱乐部辅助,wepoker透视脚本免费使用视频,靠谱教程(真实有挂)是一款可以让一直...
总算了解!wepoker破解版... 总算了解!wepoker破解版内购,wpk透视插件,2025新版技巧(有挂教学);wepoker破解...
盘点十款!情怀游戏辅助器破解版... 盘点十款!情怀游戏辅助器破解版,hhpoker为什么一直输,曝光教程(有挂工具);情怀游戏辅助器破解...
一分钟了解!潮汕汇鱼虾蟹修改器... 一分钟了解!潮汕汇鱼虾蟹修改器,wepoker辅助脚本,wpk教程(有挂功能);一、潮汕汇鱼虾蟹修改...
玩家科普!微乐智能辅助软件是真... 玩家科普!微乐智能辅助软件是真的吗,wpk透视怎么安装,AI教程(有挂总结);1、这是跨平台的微乐智...
重大通报!广西微乐小程序控制器... 重大通报!广西微乐小程序控制器,wepoker轻量版书签,wepoke教程(真实有挂);重大通报!广...
科普!酷玩联盟辅助,哈糖大菠萝... 科普!酷玩联盟辅助,哈糖大菠萝破解器,技巧教程(有挂秘诀)是一款可以让一直输的玩家,快速成为一个“必...
我来向大家传授!奇迹手游辅助,... 您好:奇迹手游辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
一起来讨论!边锋老友圈怎么开辅... 一起来讨论!边锋老友圈怎么开辅助,hhpoker是真的还是假的,黑科技教程(有人有挂);亲,有的,a...
科技揭秘!情怀莆仙外挂,约局吧... 科技揭秘!情怀莆仙外挂,约局吧德州真的有透视挂吗,力荐教程(有挂猫腻);科技揭秘!情怀莆仙外挂,约局...