我正在尝试使用以下代码实现一个广播接收器,该接收器在设备重新启动时获取广播,但无法正常工作(它应该在设备重新启动时向我发送祝酒词):
广播接收器:
[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();
}
}
}
清单文件
<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 的回答实际上也有助于解决问题
创建服务:
[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();
}
}
}
创建广播接收器:
[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 上注册 Service 和 BroadcastReceiver
<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 方法上调用服务:
Intent serviceIntent = new Intent(context, typeof(RebootService));
context.StartService(serviceIntent);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句