如何实现被杀MAUI关键应用的自动重启?含Android 14适配方案
如何实现被杀MAUI关键应用的自动重启?
我原本通过Android前台服务实现应用被杀后的重启逻辑:借助READ_CALL_LOG权限监控日志,发现应用被杀时启动新的Main Activity。但实际测试中遇到两个问题:
- 应用被杀后定时器回调停止工作,无日志输出
- 进程监控显示服务在运行、应用已启动,但界面未在用户桌面显示
问题解决
问题根源在于Android 14需要指定前台服务类型。以下是实现后台服务的代码及AndroidManifest.xml配置:
后台服务代码
using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Util; using AndroidX.Core.App; namespace MauiAppNeverKilled.Platforms.Android; [Service(Exported = true, ForegroundServiceType = global::Android.Content.PM.ForegroundService.TypeSpecialUse)] internal class MyBackgroundService : Service { Timer timer = null; int myId = new object().GetHashCode(); int BadgeNumber = 0; private readonly IBinder binder = new LocalBinder(); NotificationCompat.Builder notification; //HubConnection hubConnection; public class LocalBinder : Binder { public MyBackgroundService GetService() { return GetService(); } } public override IBinder OnBind(Intent intent) { return binder; } public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { var input = intent.GetStringExtra("inputExtra"); var notificationIntent = new Intent(this, typeof(MainActivity)); notificationIntent.SetAction("USER_TAPPED_NOTIFIACTION"); var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, PendingIntentFlags.Immutable); // 增加通知角标数字 BadgeNumber++; notification = new NotificationCompat.Builder(this, MainApplication.ChannelId) .SetContentText(input) .SetSmallIcon(Resource.Drawable.dotnet_bot) .SetAutoCancel(false) .SetContentTitle("服务运行中") .SetPriority(NotificationCompat.PriorityDefault) .SetContentIntent(pendingIntent); notification.SetNumber(BadgeNumber); // 根据Android版本启动前台服务 int sdkVersion = (int)Build.VERSION.SdkInt; if (Build.VERSION.SdkInt >= BuildVersionCodes.UpsideDownCake) StartForeground(myId, notification.Build(), ForegroundService.TypeSpecialUse); else { StartForeground(myId, notification.Build()); } // 定时检查应用是否关闭 timer = new Timer(Timer_Elapsed, notification, 0, 3000); return StartCommandResult.Sticky; } /// <summary> /// 定时器回调方法 /// </summary> /// <param name="state"></param> async void Timer_Elapsed(object state) { AndroidServiceManager.IsRunning = true; var activity = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity; if(activity == null || activity.IsDestroyed || activity.IsFinishing) { OpenPackage(package); } Log.Info("mauneverkilled", $"后台服务定时器 - {DateTime.Now.ToString()}"); } void OpenPackage(string packageName) { var appScreen = new Intent(this, typeof(MainActivity)); appScreen.SetFlags(ActivityFlags.NewTask | ActivityFlags.BroughtToFront); appScreen.SetAction("START_ACTION"); appScreen.PutExtra("packageName", packageName); this.StartActivity(appScreen); } }
AndroidManifest.xml配置
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" android:minSdkVersion="34" />
内容的提问来源于stack exchange,提问作者Vladimir B
相关产品推荐
相关产品推荐

