尽管您无法从接收器中显示 AlertDialog,因为它需要 ActivityContext。
您有另一种解决方案来显示来自 Receiver 的 Activity(例如 AlertDialog)。这个有可能。
要将 Activity 作为对话框启动,您应该将清单中的 Activity 主题设置为<activity android:theme="@android:style/Theme.Dialog" />
在 Android 中将任何 Activity 设置为警报对话框 http://www.codeproject.com/Tips/623446/Style-Any-Activity-as-an-Alert-Dialog-in-Android
要从接收器启动活动,请使用类似的代码
//Intent mIntent = new Intent();
//mIntent.setClassName("com.test", "com.test.YourActivity");
Intent mIntent = new Intent(context,YourActivity.class) //Same as above two lines
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
不使用来自接收器的 AlertDialog 的另一个原因(即使您设法显示 AlertDialog)是
BroadcastReceiver 对象仅在调用期间有效
到 onReceive(上下文,意图)。一旦你的代码从此返回
函数时,系统认为该对象已完成并且不再
积极的。
这对您在
onReceive(Context, Intent) 实现:任何需要的东西
异步操作不可用,因为您需要
从函数返回以处理异步操作,但在
此时广播接收器不再活动,因此
系统可以在异步操作之前杀死它的进程
完成。
尤其,您不能显示对话框或绑定到服务
在广播接收器内。对于前者,您应该使用
通知管理器 API。对于后者,您可以使用
Context.startService() 向服务发送命令。More... http://developer.android.com/reference/android/content/BroadcastReceiver.html
因此,更好的方法是“显示通知”,替代方法是“使用活动作为警报......”
快乐编码:)