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

相关内容

热门资讯

黑科技游戏(wepOkE)黑科... 黑科技游戏(wepOkE)黑科技设备(黑科技)黑科技ai(一贯存在有挂)1、这是跨平台的黑科技,在线...
详细辅助(微扑克)ai胜率(辅... 详细辅助(微扑克)ai胜率(辅助挂)ai软件(切实是有挂)1. ai辅助创建新账号,点击进入游戏后,...
透视辅助挂(WPk)德州透视外... 透视辅助挂(WPk)德州透视外挂(黑科技)有透视辅助(果然有挂)是一款可以让一直输的玩家,快速成为一...
透视能赢(WPK)透视挂会被封... 透视能赢(WPK)透视挂会被封号吗(黑科技)透视辅助工具的使用教程(果然真的有挂)1. ai辅助创建...
攻略辅助(微扑克)辅助插件挂(... 攻略辅助(微扑克)辅助插件挂(辅助挂)职业代打(其实存在有挂)1. ai辅助创建新账号,点击进入游戏...
普及辅助(微扑克)ai胜率(辅... 普及辅助(微扑克)ai胜率(辅助挂)ai分析器(一直是有挂)1、构建自己的微扑克辅助插件;2、选择您...
教你辅助(微扑克)ai分析器(... 1、教你辅助(微扑克)ai分析器(辅助挂)ai胜率(都是有挂);代表性(透视辅助软件透明挂)高科技在...
详细辅助(微扑克)的辅助工具苹... 详细辅助(微扑克)的辅助工具苹果(辅助挂)的辅助工具苹果(本来是有挂)是一款可以让一直输的玩家,快速...
黑科技辅助(微扑克)职业代打(... 黑科技辅助(微扑克)职业代打(辅助挂)ai辅助神器(确实是有挂);无聊就玩这款真的有辅助,无限炸弹无...
黑科技透明(wepOke)辅助... 黑科技透明(wepOke)辅助有挂吗(黑科技)辅助挂(都是是真的有挂)1、ai辅助优化,发牌逻辑科技...