我正在使用AlarmManager的服务,每30分钟触发一次我的服务接收器"用于调度通知。为了测试的目的,我已经降低了这个间隔。我的应用程序和它的服务运行完全正常并且能够提供Notifications.However在重新启动后我的服务突然停止并且消息被传递说" App停止工作"。
我写过这段代码的灵感源自here,here以及其他许多SO问题,过去12小时内一直试图解决这个问题。我怀疑问题出现在RebootReceiver或我的清单中。但是代码很简单,适用于其他人。
我的App Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="Namaz_Pro.Namaz_Pro" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="Namaz Pro">
<receiver android:name=".ServiceReceiver" />
<receiver android:name=".NotificationPublisher" />
<receiver android:name=".RebootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service android:name=".NotificationService"/>
</application>
</manifest>
我的RebootReceiver:
[BroadcastReceiver]
class RebootReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if ("android.intent.action.BOOT_COMPLETED".Equals(intent.Action))
{
Intent startServiceIntent = new Intent(context, typeof(NotificationService));
context.StartService(startServiceIntent);
}
}
}
我的服务:
[Service]
class NotificationService : Android.App.Service
{
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
var alarmIntent = new Intent(this, typeof(ServiceReceiver));
var pending = PendingIntent.GetBroadcast(this, 1234567, alarmIntent, PendingIntentFlags.UpdateCurrent);
var alarmManager = GetSystemService(AlarmService) as AlarmManager;
alarmManager.SetRepeating(AlarmType.RtcWakeup, App_Code.helperMethods.CurrentTimeMillis() + 10000, 60000 , pending);
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
base.OnDestroy();
//Log.Debug(TAG, "Simple Service Destroyed at {0}.", DateTime.UtcNow);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
我的服务接收者:
[BroadcastReceiver]
public class ServiceReceiver : BroadcastReceiver
{
notificationHelper.setUpNotifications(Android.App.Application.Context);
}
}