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、乐鱼透视辅助软件激活码多个强度级别选择2...
教程攻略!多乐跑得快开挂功能技... 教程攻略!多乐跑得快开挂功能技巧,多乐跑得快其实真的是有开挂技巧1、用户打开应用后不用登录就可以直接...
揭秘!天天摸麻将透视功能神器,... 揭秘!天天摸麻将透视功能神器,天天摸麻将总是是真的有透视神器进入游戏-大厅左侧-新手福利-激活码辅助...
重大发现!同城游牛鬼透视功能a... 重大发现!同城游牛鬼透视功能app,同城游牛鬼本来真的有透视app1、完成同城游牛鬼有辅助插件,帮助...
揭秘攻略!宝龙互娱透视挂功能插... 揭秘攻略!宝龙互娱透视挂功能插件,宝龙互娱总是真的有透视挂插件该软件可以轻松地帮助玩家将宝龙互娱外卦...
玩家攻略!福建天天十三水透视挂... 玩家攻略!福建天天十三水透视挂功能app,福建天天十三水好像存在有透视挂app1、玩家攻略!福建天天...
玩家必用!27棋牌开挂功能插件... 玩家必用!27棋牌开挂功能插件,27棋牌确实真的有开挂插件1、这是跨平台的27棋牌轻量版有透视,在线...
玩家攻略!同城游牛鬼透视功能a... 玩家攻略!同城游牛鬼透视功能app,同城游牛鬼一直是真的有透视app小薇(辅助器软件下载)致您一封信...
我来教大家!大众茶苑透视挂功能... 我来教大家!大众茶苑透视挂功能工具,大众茶苑一直是有透视挂工具1、大众茶苑有没有辅助教程、大众茶苑有...
重大科普!天天乐清麻将开挂功能... 重大科普!天天乐清麻将开挂功能app,天天乐清麻将都是是真的有开挂app1、在天天乐清麻将插件功能辅...