我的AndroidManifest
,Broadcastreceiver
和服務類別如下所示。設備啓動時我的BroadcastReceiver不工作
DetectBootUp.cs:
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class DetectBootUp : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent bootUp = new Intent(context, typeof(AndroidService));
context.StartService(bootUp);
}
}
AndroidService.cs
[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", 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">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="NotificationExample">
<receiver
android:name=".DetectBootUp"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
<service android:name=".AndroidService"
android:enabled="true"
android:exported="false">
</service>
</application>
</manifest>
MainActivity.cs
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
StartService(new Android.Content.Intent(Application.Context, typeof(AndroidService)));
}
}
當設備重新啓動時,我希望執行services類中的進程。但它給了一個錯誤。爲什麼? 當我運行該應用程序時,它工作正常,但我希望它在設備重新啓動時自動執行。可能在接收器上有錯誤,但我無法找到位置。
什麼是錯誤?你有堆棧跟蹤嗎? – Demitrian
不要堆棧跟蹤。我不知道stacktrace :) – oflu1071