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脚本!WePoKer教程... WPK脚本!WePoKer教程透视ai,德州局透视脚本下载安装最新版本,其实存在有ai透视步骤1)德...
WPK德州局!德扑之星神器辅助... WPK德州局!德扑之星神器辅助器ai,哈糖大菠萝攻略,竟然是真的有ai辅助器方式一、哈糖大菠萝攻略游...
WPK安装!wpk工具开挂ai... WPK安装!wpk工具开挂ai,AApoker设置,原来存在有ai开挂绝活1、全新机制【AApoke...
WPK工具!AApoker技巧... WPK工具!AApoker技巧辅助器ai,来玩app 德州 辅助,竟然是真的有ai辅助器课程1、该软...
WPK下载!WPKapp辅助a... WPK下载!WPKapp辅助ai,wpk系统是否存在作弊行为,好像真的是有ai辅助指引1、完成wpk...
WPK有透视!aapoker教... WPK有透视!aapoker教程透视ai,agpoker辅助,原来真的是有ai透视策略1、WPK有透...
WPK多开!红龙PoKer软件... WPK多开!红龙PoKer软件开挂ai,AApoker安全,确实存在有ai开挂步骤1、游戏颠覆性的策...
WPK购买!WPK插件辅助器a... WPK购买!WPK插件辅助器ai,约局吧能不能开挂,一直有ai辅助器模板1、下载好约局吧能不能开挂脚...
WPK辅助器!wpk工具辅助a... WPK辅助器!wpk工具辅助ai,aapoker透视脚本入口,一直存在有ai辅助方式该软件可以轻松地...
WPK辅助器!aapoker技... WPK辅助器!aapoker技巧开挂ai,福建大菠萝万能辅助器,竟然有ai开挂模板1、超多福利:超高...