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可以辅助吗,w... 教学盘点!wpk可以辅助吗,wepoker有机器人吗,必赢方法(一贯确实有挂)-哔哩哔哩;wepok...
玩家必看科普!德普之星透视辅助... 玩家必看科普!德普之星透视辅助软件,hhpoker辅助挂下载,我来教教你(其实是有挂的)-哔哩哔哩;...
透视有挂!wejoker辅助脚... 透视有挂!wejoker辅助脚本,we poker辅助器v3.3,细节揭秘(一直确实有挂)-哔哩哔哩...
重大通报!wepoker亲友圈... 重大通报!wepoker亲友圈有用吗,wpk俱乐部怎么辅助,规律教程(果然是有挂的)-哔哩哔哩;亲真...
必备科技!德普之星有辅助软件吗... 必备科技!德普之星有辅助软件吗,hhpoker是内部控制吗,详细教程!(一直确实有挂)-哔哩哔哩;人...
揭秘关于!德州局hhpoker... 揭秘关于!德州局hhpoker,wepoker有人用过吗,线上教程(一贯真的有挂)-哔哩哔哩;超受欢...
必备辅助推荐!wepoker破... 《必备辅助推荐!wepoker破解游戏盒子,aapoker插件下载,揭秘教程(原来有挂)-哔哩哔哩》...
我来分享!wepoker私人局... 我来分享!wepoker私人局透视插件,wepoker轻量版有透视吗,2026版教程(原来真的有挂)...
透视规律!aapoker如何设... 透视规律!aapoker如何设置胜率,德州透视竞技联盟,2026教程(原来是有挂的)-哔哩哔哩;1、...
实测教程!哈糖大菠萝有挂吗5个... 实测教程!哈糖大菠萝有挂吗5个常用方法,pokeplus脚本,黑科技教程(一直真的是有挂)-哔哩哔哩...