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辅助器,微扑克全自动机器人,总结教程(有挂透明)-哔哩哔哩;是一款可以让一直输的玩...
黑科技插件!Wpk有挂吗,we... 黑科技插件!Wpk有挂吗,wepoke透明挂在哪买,2025新版教程(有挂攻略)-哔哩哔哩是一款可以...
黑科技神器!德扑ai智能,微扑... 黑科技神器!德扑ai智能,微扑克德州专用辅助器,爆料教程(有挂规律)-哔哩哔哩是一款可以让一直输的玩...
黑科技ai!wpk德州有挂吗,... 黑科技ai!wpk德州有挂吗,德州之星辅助器多少钱,教你攻略(有挂透明)-哔哩哔哩1、不需要AI权限...
黑科技挂!wepokeai代打... 黑科技挂!wepokeai代打辅助,wpk透明挂,科技教程(有挂总结)-哔哩哔哩1、许多玩家不知道w...
黑科技ai!wpk德州职业代打... 黑科技ai!wpk德州职业代打,wepoke怎么看有没有外挂,详细教程(有挂透明)-哔哩哔哩1、we...
黑科技机器人!wepoke黑科... 黑科技机器人!wepoke黑科技ai,aapoker有假吗,辅助教程(有挂黑科技)-哔哩哔哩1)we...
黑科技软件!红龙扑克辅助器下载... 黑科技软件!红龙扑克辅助器下载,aapoker辅助透视,软件教程(有挂教学)-哔哩哔哩;是一款可以让...
黑科技软件!wepoke黑科技... 黑科技软件!wepoke黑科技ai,德扑之星有猫腻,玩家教你(有挂教学)-哔哩哔哩1、德扑之星有猫腻...
黑科技辅助!aapoker有外... 黑科技辅助!aapoker有外挂吗,微扑克透牌软件,普及教程(有挂透明)-哔哩哔哩1.微扑克透牌软件...