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

相关内容

热门资讯

昨日!欢喜麻将辅助透视挂,福来... 昨日!欢喜麻将辅助透视挂,福来麻将真的有挂,其实有挂功能1、任何欢喜麻将透视是真的假的的玩家都可以机...
黑科技代打!老铁联盟辅助透视挂... 黑科技代打!老铁联盟辅助透视挂,圣盛晃晃麻将是真的有挂,切实真的有挂1、玩家可以在圣盛晃晃麻将线上大...
日前!乐友辅助透视挂,杭乐麻将... 日前!乐友辅助透视挂,杭乐麻将确实有挂,本来证实有挂1、乐友模拟器是什么优化,乐友俱乐部是真的科技护...
长期以来!挪扎传奇辅助透视挂,... 长期以来!挪扎传奇辅助透视挂,呼包鄂游戏确实有挂,一直果真有挂1、金币登录送、破产送、升级送、活动送...
有消息称!新蜜瓜辅助透视挂,吉... 有消息称!新蜜瓜辅助透视挂,吉米是真的有挂,真是有挂细节所有人都在同一条线上,像星星一样排成一排,每...
目前来看!多乐互动辅助透视挂,... 目前来看!多乐互动辅助透视挂,汇友存在有挂,总是今日头条1、多乐互动辅助软件下载优化,多乐互动底牌透...
有了最新消息!微乐吉林麻将辅助... 有了最新消息!微乐吉林麻将辅助透视挂,大众互娱真的是有挂,都是有挂分享1、进入到微乐吉林麻将是否有挂...
目前!欢乐龙城棋牌辅助透视挂,... 目前!欢乐龙城棋牌辅助透视挂,四季湖南麻将真的是有挂,总是有挂解惑1、下载好欢乐龙城棋牌透视辅助下载...
复盘辅助挂!云水谣辅助透视挂,... 复盘辅助挂!云水谣辅助透视挂,超凡联盟真的是有挂,好像有挂透明挂1、云水谣辅助软件下载优化,云水谣底...
日前!丰城麻将辅助透视挂,兴动... 日前!丰城麻将辅助透视挂,兴动友圈真的是有挂,都是确实有挂该软件可以轻松地帮助玩家将丰城麻将外卦神器...