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

相关内容

热门资讯

玩家实测!微扑克wpk辅助透视... 玩家实测!微扑克wpk辅助透视,微扑克如何让系统发好牌(微扑克)都是真的有挂(有挂解密)-哔哩哔哩1...
一分钟了解!德州微扑克外挂,微... 一分钟了解!德州微扑克外挂,微扑克透牌(微扑克)真是存在有挂(果真有挂)-哔哩哔哩德州微扑克外挂是一...
玩家必备教程!微扑克辅助挂,微... 玩家必备教程!微扑克辅助挂,微扑克有挂么(微扑克)果然有挂(有挂教程)-哔哩哔哩;微扑克辅助挂辅助器...
热点推荐!微扑克透牌软件,微扑... 热点推荐!微扑克透牌软件,微扑克ai机器人(微扑克)其实是真的有挂(发现有挂)-哔哩哔哩1、游戏颠覆...
总算了解!微扑克辅助插件挂,微... 总算了解!微扑克辅助插件挂,微扑克ai机器人(微扑克)本来真的有挂(有挂教学)-哔哩哔哩1、用户打开...
玩家必用!微扑克辅牌器,微扑克... 玩家必用!微扑克辅牌器,微扑克如何让系统发好牌(微扑克)一直是真的有挂(有挂解密)-哔哩哔哩1、微扑...
普及知识!微扑克透明挂,微扑克... 普及知识!微扑克透明挂,微扑克透牌(微扑克)原来是真的有挂(新版有挂)-哔哩哔哩1、任何微扑克透明挂...
分享一款!微扑克职业代打,微扑... 分享一款!微扑克职业代打,微扑克ai机器人(微扑克)一直真的有挂(有挂方式)-哔哩哔哩1、首先打开微...
总算了解!微扑克透牌真假的,微... 总算了解!微扑克透牌真假的,微扑克如何让系统发好牌(微扑克)都是有挂(有挂细节)-哔哩哔哩;1、微扑...
盘点几款!微扑克ai算牌器,微... 盘点几款!微扑克ai算牌器,微扑克有挂么(微扑克)果然是真的有挂(有挂细节)-哔哩哔哩1、完成微扑克...