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、实时透视辅助更新:用户可以...
程序员教你!wepoker私人... 程序员教你!wepoker私人局俱乐部(辅助挂)确实存在有挂(有挂教程辅助软件)辅助器是一种具有地方...
今日科普!wepoker有透视... 今日科普!wepoker有透视功能吗(辅助挂)原来真的有挂(详细教程辅助攻略)1、打开软件启动之后找...
揭秘一下!wepokerplu... 揭秘一下!wepokerplus外挂(辅助挂)本来存在有挂(有挂助手辅助软件);1、玩家可以在透视最...
热点推荐!wpk插件辅助(辅助... 热点推荐!wpk插件辅助(辅助挂)本来真的有挂(存在有挂辅助攻略)1、任何透视是真的假的的玩家都可以...
终于知道!wepokerplu... 终于知道!wepokerplus透视脚本免费(辅助挂)果然是有挂(发现有挂辅助工具)1、让任何用户在...
六分钟了解!hhpoker辅助... 六分钟了解!hhpoker辅助软件是真的么(辅助挂)切实真的是有挂(有挂技巧辅助插件)1、该软件可以...
总算了解!wepoker私人辅... 总算了解!wepoker私人辅助器(辅助挂)本来真的是有挂(真的有挂辅助app)1、进入到是否有挂之...
教程辅助!拱趴大菠萝怎么开挂(... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
最新研发!wepoker买脚本... 最新研发!wepoker买脚本靠谱吗(辅助挂)切实真的有挂(今日头条辅助软件)最新研发!wepoke...