问题描述
我正在尝试使用以下代码实现广播接收器,该广播接收器在设备重新启动后会广播,但无法正常工作(设备重新启动后应该向我敬酒)
I am trying to implement a broadcast receiver that gets the broadcast when the device has been rebooted, but is not working (it is supposed to send me a toast when the device has rebooted) with the following code:
广播接收器:
[BroadcastReceiver]
public class RebootReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (Intent.ActionBootCompleted.Equals(intent.Action))
{
Toast.MakeText(
context,
"Your app has been rebooted!",
ToastLength.Long).Show();
}
}
}
Manifest.xml
Manifest.xml
<receiver android:name=".RebootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
清单中的权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
希望有帮助,谢谢
推荐答案
我已经解决了这个问题,@FreakyAli的答案实际上也有助于获得解决方案
I have solved the problem, the answer of @FreakyAli has also helped in fact of getting the solution
创建服务:
[Service(Name = "com.companyname.app.RebootService")]
public class RebootService : Service
{
public override void OnCreate()
{
base.OnCreate();
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Toast.MakeText(this, "Service STARTED!", ToastLength.Long).Show();
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
base.OnDestroy();
Toast.MakeText(this, "Service STOPED", ToastLength.Long).Show();
}
}
}
创建BroadcastReciver:
Create BroadcastReciver:
[BroadcastReceiver(Enabled =true, Name ="com.companyname.Sortex.RebootReceiver")]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class RebootReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
}
}
在AndroidManifest.xml中注册服务和BroadcastReceiver
register Service and BroadcastReceiver on AndroidManifest.xml
<service android:name="com.companyname.app.RebootService"/>
<receiver android:name="com.companyname.app.RebootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
在广播接收器的OnReceive方法上调用服务:
Call the service on the OnReceive method of the Broadcast receiver:
Intent serviceIntent = new Intent(context, typeof(RebootService));
context.StartService(serviceIntent);
这篇关于“重新启动接收器"无法在android系统上运行[Xamarin.Android]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!