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

相关内容

热门资讯

热门推荐作弊器!十三水作弊器多... 您好,十三水这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游...
玩家必备教程外挂!葫芦娃大厅外... 玩家必备教程外挂!葫芦娃大厅外挂多功能AIapp,葫芦娃大厅真是是有外挂app1、金币登录送、破产送...
记者发布透视器!海螺互娱透视器... 记者发布透视器!海螺互娱透视器多功能AI方法,海螺互娱切实是真的有透视器方法海螺互娱破解侠是真的助透...
玩家必看教程开挂!荔枝娱乐开挂... 玩家必看教程开挂!荔枝娱乐开挂多功能AI方法,荔枝娱乐果然是真的有开挂方法运荔枝娱乐辅助工具,进入游...
每日必看教程透视挂!年年大厅透... 每日必看教程透视挂!年年大厅透视挂多功能AI插件,年年大厅一直真的有透视挂插件1、操作简单,无需年年...
今日头条外挂!王者众娱外挂多功... 今日头条外挂!王者众娱外挂多功能AI插件,王者众娱竟然存在有外挂插件进入游戏-大厅左侧-新手福利-激...
必备科技作弊器!淮滨互娱作弊器... 必备科技作弊器!淮滨互娱作弊器多功能AI工具,淮滨互娱真是真的是有作弊器工具1、进入到淮滨互娱是否有...
我来分享作弊器!本地互娱作弊器... 我来分享作弊器!本地互娱作弊器多功能AI技巧,本地互娱本来是有作弊器技巧本地互娱透视方法中分为三种模...
终于懂了作弊器!众享互娱作弊器... 终于懂了作弊器!众享互娱作弊器多功能AI方法,众享互娱好像存在有作弊器方法运众享互娱辅助工具,进入游...
带你了解透视挂!葫芦娃大厅透视... 带你了解透视挂!葫芦娃大厅透视挂多功能AIapp,葫芦娃大厅好像存在有透视挂app1、该软件可以轻松...