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

相关内容

热门资讯

重大消息!聚财平台辅助(辅助挂... 【福星临门,好运相随】;重大消息!聚财平台辅助(辅助挂)wepoker透视有用吗(起初真的有挂);暗...
玩家必备攻略!科乐游戏辅助脚本... 玩家必备攻略!科乐游戏辅助脚本视频(辅助挂)竞技联盟破解版最新版(本来真的是有挂)是一款可以让一直输...
详细说明!乐达app辅助(辅助... 详细说明!乐达app辅助(辅助挂)aapoker免费透视脚本(往昔有挂);小薇(透视辅助)致您一封信...
记者发布!jj斗地主外开挂(辅... 记者发布!jj斗地主外开挂(辅助挂)德普之星透视辅助软件激活码(从前存在有挂);1、很好的jj斗地主...
一分钟了解!广东雀神祈福真的有... 一分钟了解!广东雀神祈福真的有用吗(辅助挂)wepoker好友房开挂(先前真的有挂);1、超多福利:...
重大来袭!吉安中至小程序(辅助... 重大来袭!吉安中至小程序(辅助挂)wepoker永久免费脚本(确实真的有挂);人气非常高,ai更新快...
我来向大家传授!微信小程序多功... 您好:微信小程序多功能辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
大家学习交流!途游大作战辅助(... 您好:途游大作战辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
攻略讲解!花舍辅助(辅助挂)w... 您好,花舍辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏...
每日必看!老k麻将辅助器(辅助... 【福星临门,好运相随】;每日必看!老k麻将辅助器(辅助挂)wepoker免费脚本咨询(本来是真的有挂...