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)大唐麻雀辅助器怎么设置免费钻石...
据目击者称!新道游app辅助器... 据目击者称!新道游app辅助器!原来是有辅助修改器(真的有挂)-哔哩哔哩新道游app辅助器是不是有人...
现有关情况通报如下!开心网辅助... 现有关情况通报如下!开心网辅助工具!真是存在有辅助平台(有挂工具)-哔哩哔哩;暗藏猫腻,小编详细说明...
出乎意料的是!上饶辅助!好像是... 出乎意料的是!上饶辅助!好像是有辅助修改器(有挂方法)-哔哩哔哩1、上饶辅助破解器简单,上饶辅助机器...
据相关数据显示!广西友乐app... 据相关数据显示!广西友乐app辅助工具!确实存在有辅助器(有挂攻略)-哔哩哔哩1、游戏颠覆性的策略玩...
今天上午!新上游通用挂!原来真... 今天上午!新上游通用挂!原来真的有辅助平台(有挂总结)-哔哩哔哩;一、新上游通用挂游戏安装教程牌型概...
有了最新消息!大唐山西辅助软件... 有了最新消息!大唐山西辅助软件!其实存在有辅助工具(有挂详情)-哔哩哔哩1、大唐山西辅助软件免费脚本...
值得注意的是!微乐贵阳捉鸡麻将... 值得注意的是!微乐贵阳捉鸡麻将开挂!其实真的是有辅助神器(有挂技巧)-哔哩哔哩1、玩家可以在微乐贵阳...
据报道!广东雀神智能插件安装软... 据报道!广东雀神智能插件安装软件!总是是真的辅助工具(有挂猫腻)-哔哩哔哩1、游戏颠覆性的策略玩法,...
今天下午!小程序牵手跑得快辅助... 今天下午!小程序牵手跑得快辅助器!一直是有辅助下载(有挂规律)-哔哩哔哩1、小程序牵手跑得快辅助器公...