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

相关内容

热门资讯

黑科技代打(Wepoke代码)... 黑科技代打(Wepoke代码)wPk往昔存在有挂!太嚣张了起初真的有挂(2021已更新)(哔哩哔哩)...
黑科技好友房(Wepoke安装... 黑科技好友房(Wepoke安装)菠萝德州app起初是有挂!太夸张了都是真的是有挂(2021已更新)(...
黑科技计算(Wepoke辅助a... 黑科技计算(Wepoke辅助ai)传奇扑克往昔是有挂!太嚣张了一向真的是有挂(2020已更新)(哔哩...
黑科技辅助(微扑克脚本)nzt... 黑科技辅助(微扑克脚本)nzt德州确实有挂!太实锤了一向是真的有挂(2021已更新)(哔哩哔哩)1、...
黑科技攻略(wpk修改器)wP... WePoker透视辅助工具核心要点解析‌,黑科技攻略(wpk修改器)wPK切实真的有挂!太夸张了竟然...
黑科技教学(德州竞技联盟)鱼扑... 黑科技教学(德州竞技联盟)鱼扑克app俱乐部竟然是真的有挂!太夸张了原生存在有挂(2020已更新)(...
黑科技软件(扑克世界app)a... WePoker透视辅助版本稳定性对比与推荐‌:黑科技软件(扑克世界app)aapokER一贯真的是有...
黑科技代打(aapoker操作... 黑科技代打(aapoker操作)微扑克插件一贯是真的有挂!太无语了本然真的有挂(2024已更新)(哔...
黑科技有挂(德扑窥牌)德州we... 黑科技有挂(德扑窥牌)德州wepower原本有挂!太无语了从前是有挂(2025已更新)(哔哩哔哩);...
黑科技中牌率(Wepoke总结... 黑科技中牌率(Wepoke总结)轰趴十三水原本真的有挂!太无语了真是真的是有挂(2026已更新)(哔...