您好我在尝试在AsyncTask中运行警报时遇到了一些麻烦。每当运行带有上下文的内容时,应用程序就会崩溃,就像尝试让警报出现一样。
我确信,错误是由于错误的" context"或类似的东西。
我从GCM类调用我的AsyncTask类,如下所示:
GCM.java:
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
// displayMessage(context, message);
// notifies user
generateNotification(context, message);
runAsync(context);
// update database
}
// here I want to run my asyncTask
private void runAsync(Context context){
TestActivity = new TestActivity(context);
task.execute();
}
TestActivity.java:
Context mContext;
public TestActivity(Context context) {
this.mContext = context;
}
// Progress Dialog
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
productsList = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
// here when It shall show the alert it crashes... with the following error
pDialog.show();
}
F/AndroidRuntime(19976): FATAL EXCEPTION: IntentService[GCM-980252920256-1]
F/AndroidRuntime(19976): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
F/AndroidRuntime(19976): at android.view.ViewRootImpl.setView(ViewRootImpl.java:792)
F/AndroidRuntime(19976): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
F/AndroidRuntime(19976): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
F/AndroidRuntime(19976): at android.app.Dialog.show(Dialog.java:282)
F/AndroidRuntime(19976): at com.test.app.TestActivity.onPreExecute(TestActivity.java:72)
F/AndroidRuntime(19976): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
F/AndroidRuntime(19976): at android.os.AsyncTask.execute(AsyncTask.java:534)
F/AndroidRuntime(19976): at com.test.app.GCM.asyncTaskRun(GCM.java:63)
F/AndroidRuntime(19976): at com.test.app.GCM.onMessage(GCM.java:55)
F/AndroidRuntime(19976): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:223)
F/AndroidRuntime(19976): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
F/AndroidRuntime(19976): at android.os.Handler.dispatchMessage(Handler.java:99)
F/AndroidRuntime(19976): at android.os.Looper.loop(Looper.java:176)
F/AndroidRuntime(19976): at android.os.HandlerThread.run(HandlerThread.java:60)
我的错误在哪里?
答案 0 :(得分:1)
ProgressDialog需要一个Activity作为Context(在Android中这是一个糟糕的设计,Context并不总是必需的Context)。
您应该打开一个看起来像对话框的活动:
答案 1 :(得分:0)
将上下文作为Activity
传递而不是ApplicationContext
。这两个类都扩展了Context
类。