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... 您好,wepoke透明黑科技这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多...
黑科技计算!菠萝德州辅助神器(... 黑科技计算!菠萝德州辅助神器(aapoker辅助工具ai)原生是有挂(有挂透视)-哔哩哔哩是一款可以...
黑科技教学!wepoke软件规... 黑科技教学!wepoke软件规律(wepoke智能ai)本来是真的有挂(有挂分析)-哔哩哔哩1、we...
黑科技线上!哈糖大菠萝洗牌(德... 黑科技线上!哈糖大菠萝洗牌(德扑ai智能机器人线上代打)原来真的是有挂(有挂教程)-哔哩哔哩1、实时...
黑科技免费!wepoke到底有... 1、黑科技免费!wepoke到底有挂(德州ai软件购买)其实是真的有挂(有挂秘籍)-哔哩哔哩;该软件...
黑科技ai!扑克时间有后台控制... 黑科技ai!扑克时间有后台控制(微扑克如何让系统发好牌)本来是真的有挂(了解有挂)-哔哩哔哩(1)黑...
黑科技系统!wpk辅助器安装(... 黑科技系统!wpk辅助器安装(wpk最新黑科技)本然真的是有挂(有挂辅助)-哔哩哔哩1)wpk最新黑...
黑科技存在!微扑克辅助插件挂(... 黑科技存在!微扑克辅助插件挂(德扑ai机器人软件开发)切实是有挂(有挂存在)-哔哩哔哩您好,德扑ai...
黑科技线上!wepoke插件(... 1、黑科技线上!wepoke插件(德扑ai机器人软件开发)原本是真的有挂(有人有挂)-哔哩哔哩;代表...
黑科技数据!鱼扑克软件辅助(德... 黑科技数据!鱼扑克软件辅助(德扑ai智能机器人)确实存在有挂(有挂辅助)-哔哩哔哩(1)黑科技数据!...