我想在设备重启时自动启动服务。之后,我希望执行服务中的操作。我写了一个代码,但在重启设备时它失败了。我有2节课。这些是' AdroidService
'和' DetectBootUp
'。我认为' AndroidManifest.xml'。
DetectBootUp.cs
namespace NotifyExp2.Droid.ReminderService
{
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
class DetectBootUp : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent bootUp = new Intent(context.ApplicationContext, typeof(AndroidService));
bootUp.AddFlags(ActivityFlags.ExcludeStoppedPackages);
bootUp.AddFlags(ActivityFlags.IncludeStoppedPackages);
context.StartService(bootUp);
}
}
}
AndroidService.cs
namespace NotifyExp2.Droid.ReminderService
{
[Service]
public class AndroidService : Service
{
public override void OnCreate()
{
Toast.MakeText(this, "Service Created", ToastLength.Long).Show();
Log.Debug("BroadCastReceiverBoot", "OnCreate");
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnDestroy()
{
Toast.MakeText(this, "Service Destroyed", ToastLength.Long).Show();
Log.Debug("BroadCastReceiverBoot", "onDestroy");
ApplicationContext.StartService(new Intent(ApplicationContext, typeof(AndroidService)));
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Toast.MakeText(this, "Service Started - " + DateTime.Now.Hour + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(), ToastLength.Long).Show();
Log.Debug("BroadCastReceiverBoot", "OnStart");
return StartCommandResult.Sticky;
}
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="NotificationExample"
android:enabled="true">
<receiver
android:name=".DetectBootUp"
android:enabled="true"
android:exported="false"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
<service android:name=".AndroidService"
android:enabled="true"
android:exported="false">
</service>
</application>
</manifest>