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、下载好雀神广东插件智能解码脚本...
一分钟了解!多乐手游辅助软件,... 一分钟了解!多乐手游辅助软件,广东闲来app辅助,详细攻略(有挂细节)1、多乐手游辅助软件有没有辅助...
实测必看!微信小程序功夫川辅助... 实测必看!微信小程序功夫川辅助,吉林心悦游戏辅助,详细技巧(有挂辅助)运微信小程序功夫川辅助辅助工具...
六分钟了解!陕西三代辅助器免费... 六分钟了解!陕西三代辅助器免费,广西八一字牌辅助,详细挂(新版有挂)1、陕西三代辅助器免费破解器简单...
科技介绍!创思维激k软件助手,... 科技介绍!创思维激k软件助手,广西微乐小程序控制器,详细方法(有挂规律)1、游戏颠覆性的策略玩法,独...
揭秘真相!杭州都莱大菠萝辅助器... 揭秘真相!杭州都莱大菠萝辅助器,鸿狐大厅脚本,详细软件(有挂解密)1、任何杭州都莱大菠萝辅助器透视是...
记者发布!微友圈app辅助工具... 记者发布!微友圈app辅助工具,微信小程序加速脚本,详细工具(真的有挂)1、全新机制【微信小程序加速...