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购买透视经验!wepok... WPK购买透视经验!wepoker有用吗,wpkai多功能透视插件wepoker有用吗脚本下载中分为...
解密教程辅助器!一点河北麻将a... 您好:一点河北麻将这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
WPK控制牌辅助方案!htx矩... WPK控制牌辅助方案!htx矩阵wepoker辅助,wpkai多功能辅助插件WPK控制牌辅助方案!h...
我来分享辅助!坦克大作战ai辅... 您好,坦克大作战这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家在这款游...
WPK插件开挂模块!德扑圈有透... WPK插件开挂模块!德扑圈有透视吗,智星菠萝德州ai多功能开挂插件;1、让任何用户在无需德扑圈有透视...
最新技巧!开挂!悠悠广东麻将a... 最新技巧!开挂!悠悠广东麻将ai开挂多功能插件,竟然是真的有开挂插件攻略是一款可以让一直输的玩家,快...
WPK脚本透视挂法门!wepo... WPK脚本透视挂法门!wepoker怎么设置透视,德扑之星ai多功能透视挂教程WPK脚本透视挂法门!...
AI教程辅助器!海商娱乐ai辅... AI教程辅助器!海商娱乐ai辅助器多功能插件,素来存在有辅助器教程课程主打赛后复盘的 AI 游戏攻略...
WPK控制牌辅助器手册!微扑克... 您好,微扑克辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这...
热点推荐!辅助!南通长牌ai辅... 热点推荐!辅助!南通长牌ai辅助多功能插件,原来有辅助脚本教材AI 是一款可以让一直输的玩家修复黑科...