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

相关内容

热门资讯

透视能赢"约局吧游戏... 透视能赢"约局吧游戏挂"详细辅助扑克教程(透视脚本透视)是一款可以让一直输的玩家,快速成为一个“必胜...
透视好友"红龙pok... 透视好友"红龙poker作弊指令"详细辅助曝光教程(免费脚本咨询神器);玩家必备必赢加哟《13670...
透视挂"hhpoke... 透视挂"hhpoker免费透视脚本"详细辅助新2025教程(破解器激活码透视);实战中需综合运用上述...
透视透视"hhpok... 透视透视"hhpoker辅助软件是真的么"详细辅助曝光教程(手机插件软件)1、很好的工具软件,可以解...
透视教学"wepok... 透视教学"wepoker有透视吗"详细辅助规律教程(有辅助插件神器);建议优先通过wepoker有透...
透视智能ai"wep... 透视智能ai"wepoker挂"详细辅助微扑克教程(买脚本靠谱技巧),支持语音通讯、好友开房及战队组...
透视透视"hhpok... 透视透视"hhpoker怎么开透视"详细辅助技巧教程(透视脚本免费下载pc技巧);玩家必备必赢加哟《...
透视计算"wepok... 透视计算"wepoker代打辅助"详细辅助玩家教程(智能辅助插件辅助);致您一封信;亲爱wepoke...
透视系统"拱趴大菠萝... 透视系统"拱趴大菠萝有什么挂"详细辅助2025教程(私人局俱乐部技巧)是一款可以让一直输的玩家,快速...
透视总结"xpoke... 透视总结"xpoker辅助助手"详细辅助线上教程(私人局开挂视频技巧)是一款可以让一直输的玩家,快速...