Android 从BroadcastReceive的onReceive中删除由主活动启动的ProgressDialog
我在我的Android 从BroadcastReceive的onReceive中删除由主活动启动的ProgressDialog,android,nullpointerexception,broadcastreceiver,progressdialog,Android,Nullpointerexception,Broadcastreceiver,Progressdialog,我在我的活动中启动了一个ProgressDialog,该对话框应该一直旋转,直到调用的IntentService完成,但是当我试图从onReceive中关闭ProgressDialog时,实例为null,我得到了一个NullPointerException public class myActivity extends Activity { ProgressDialog progressDialog = null; @Override protected void o
活动中启动了一个ProgressDialog
,该对话框应该一直旋转,直到调用的IntentService
完成,但是当我试图从onReceive
中关闭ProgressDialog
时,实例为null,我得到了一个NullPointerException
public class myActivity extends Activity {
ProgressDialog progressDialog = null;
@Override
protected void onCreate(Bundle stateBundle) {
super.onCreate(stateBundle);
myBroadcastReceiver broadcastReceiver = new myBroadcastReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,new IntentFilter("abc.def"));
}
....
public void runService() {
Intent myIntent = new Intent("com.example.service");
myIntent.addCategory(Intent.CATEGORY_DEFAULT);
try {
progressDialog = ProgressDialog.show(this, "Please wait ...", "Running Service.", true);
progressDialog.setCancelable(false);
startService(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Service app not found.", Toast.LENGTH_LONG).show();
}
}
public void nextStep(Intent intent) {
//do something when process is complete.
}
....
private class myBroadcastReceiver extends BroadcastReceiver
{
// Prevents instantiation
private void myBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
progressDialog.dismiss(); //<--this is where i get the exception
nextStep(intent);
}
}
}
由于某种原因,onReceive
似乎在runService
之前被调用。有时在Android上,广播接收器一注册就可以被调用。看 请在下面的链接中参考我的答案
您必须为此使用接口。它将充当事件侦听器…如果广播接收器中发生任何事情,您可以在活动中触发接口实现
请参阅帖子
我有几个问题
1) 我遵循一个示例,使用LocalBroadcastManager
注册和发送广播。但是LocalBroadcastManager
只适用于同一应用程序中的内容。我有两个独立的应用程序。所以,举个例子
而不是
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,new IntentFilter("abc.def"));
我需要
registerReceiver(broadcastReceiver,new IntentFilter("abc.def"));
2) 我的两个应用程序构建在同一个基类上,该基类包含所描述的功能。因此,应用程序B获得了自己的sendBroadcast()
,但应用程序B没有启动ProgressDialog
应用程序a有。你能在屏幕上看到进度对话框吗?是的。但是,随后被调用的服务启动一个不同的活动,该活动占据前台。因此,在出现异常时,无法看到ProgressDialog。异常不会终止该活动,因此当我返回到它时,它只是停留在ProgressDialog旋转中。所以当该活动再次出现在前景中时,您取消了ProgressDialog
?不,我不这么认为。当另一个应用程序具有前景时,将发生关闭。这是一个调用dismise的过程,异常发生在。你可以发布日志吗?我可以直观地看到progressDialog出现在错误之前。只是为了确认一下,我在调试器中运行,在调用onReceive之前,它被创建并显示了一段时间。看起来很有希望。我今天应该有时间试试这个。
registerReceiver(broadcastReceiver,new IntentFilter("abc.def"));