我创建了一个示例应用程序,它将在后台启动服务,即使从缓存中清除服务正在运行但适用于Android版本5.在Android版本8.1中不支持。
我的MainActivity.cs代码
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
//var alarmIntent = new Intent(this, typeof(AlarmReceiver));
//alarmIntent.PutExtra("title", "Hello");
//alarmIntent.PutExtra("message", "World!");
Intent intent = new Intent(NOTIFICATION_CHANNEL_ID);
intent.SetClass(this, typeof(AlarmReceiver));
var pending = PendingIntent.GetBroadcast(this, 0, intent, PendingIntentFlags.UpdateCurrent);
var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
alarmManager.SetRepeating(AlarmType.ElapsedRealtime, DateTime.Now.Millisecond, 5 * 100, pending);
}
我有AlarmReciever.cs类
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
class AlarmReceiver : BroadcastReceiver
{
Context context;
public override void OnReceive(Context context, Intent intent)
{
this.context = context;
Toast.MakeText(context, "Service is Running in background", ToastLength.Long).Show();
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
context.StartForegroundService(new Intent(context, typeof(BackgroundService)));
}
else
{
context.StartService(new Intent(context, typeof(BackgroundService)));
}
//Intent background = new Intent(context, typeof(BackgroundService));
//context.StartForegroundService(background);
}
}
从缓存中清除应用程序时,我在我的服务类中调用OnTaskRemoved方法 -
[Service]
public class BackgroundService : Service
{
public override void OnCreate()
{
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug("service", "Service Started");
//init the handler in oncreate
System.Timers.Timer Timer1 = new System.Timers.Timer();
Timer1.Start();
Timer1.Interval = 3000;
int a = 0;
Timer1.Enabled = true;
//Timer1.Elapsed += OnTimedEvent;
Timer1.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
{
Timer1.Stop();
Timer1.Start();
a++;
//Delete time since it will no longer be used.
Timer1.Dispose();
};
Timer1.Start();
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnTaskRemoved(Intent rootIntent)
{
Intent restartServiceIntent = new Intent(this, this.Class);
restartServiceIntent.SetPackage(this.PackageName);
Log.Debug("service", "Service Restarted");
PendingIntent restartServicePendingIntent = PendingIntent.GetService(this, 1, restartServiceIntent, PendingIntentFlags.OneShot);
AlarmManager alarmService = (AlarmManager)this.GetSystemService(Context.AlarmService);
alarmService.SetRepeating(AlarmType.RtcWakeup, SystemClock.CurrentThreadTimeMillis(), 30 * 1000, restartServicePendingIntent);
NotificationManager notificationManager =
(NotificationManager)GetSystemService(NotificationService);
Notification.Builder builder = new Notification.Builder(this);
Intent notificationIntent = new Intent(this, typeof(MainActivity));
PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
//set
builder.SetContentIntent(contentIntent);
builder.SetSmallIcon(Resource.Mipmap.launcher_foreground);
builder.SetContentText("Service Running in background");
builder.SetContentTitle("Service Restarted");
builder.SetAutoCancel(true);
builder.SetDefaults(NotificationDefaults.All);
notificationManager.Notify(1, builder.Build());
base.OnTaskRemoved(rootIntent);
}
}
这个代码适用于Android版本5.但是当我清除应用程序缓存并在Android版本8.1中测试时,应用程序停止了(没有点击OnTaskRemoved方法)。
任何人都可以帮助我出错的地方。谢谢你。
Android API级别26(8.0)对后台服务能够执行的操作以及持续时间实施了更严格的限制,尤其是当他们各自的应用程序不在前台时。关于这些限制究竟是什么,有一些Android documentation。
官方推荐TL; DR是 - 如果您要运行的服务是“用户可见的”,那么考虑将您的服务设为Foreground Service。 Foreground Services要求您在该服务运行时显示通知(想一想您的音频播放器在播放音乐时显示的通知)。如果没有,那么它可能由scheduling a Job处理。