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、不需要AI权限,帮助你快速的进行WPK...
一分钟教会你!智星菠萝德州辅助... 一分钟教会你!智星菠萝德州辅助挂多功能透视工具,原来真的是有挂(有挂规律)1、实时智星菠萝德州透视辅...
一起来讨论!wpk辅助挂多功能... 一起来讨论!wpk辅助挂多功能透视工具,本来是真的有挂(有挂教学)1、在wpk插件功能辅助器技巧中,...
一分钟快速了解!AAPoKer... 一分钟快速了解!AAPoKer辅助挂多功能透视工具,果然是真的有挂(有挂辅助)1、玩家可以在AAPo...
推荐十款!WPK辅助挂多功能透... 推荐十款!WPK辅助挂多功能透视工具,本来存在有挂(有挂讲解)1、完成WPK辅助器v3.3的残局,帮...
玩家必看科普!德扑之星辅助挂多... 玩家必看科普!德扑之星辅助挂多功能透视工具,一直真的有挂(有挂总结)1、这是跨平台的德扑之星轻量版有...
玩家必看科普!德扑圈辅助挂多功... 玩家必看科普!德扑圈辅助挂多功能透视工具,切实真的是有挂(发现有挂)1、许多玩家不知道德扑圈辅助怎么...
实测教程!WPK辅助挂多功能透... 实测教程!WPK辅助挂多功能透视工具,切实存在有挂(有挂详细)1、操作简单,无需WPK手机版透视脚本...
盘点一款!AAPoKer辅助挂... 盘点一款!AAPoKer辅助挂多功能透视工具,一直是有挂(有挂详情)一、AAPoKer游戏安装教程牌...
玩家科普!智星菠萝德州辅助挂多... 玩家科普!智星菠萝德州辅助挂多功能透视工具,真是是有挂(有挂方法)在进入智星菠萝德州软件靠谱后,参与...