I have created IntentService
class and performing asyncTask
but getting exception when onPreExecute()
is called at this code line pDialog.show();
AsyncHandlerService Class ---
public class AsyncHandlerService extends IntentService{
ProgressDialog pDialog;
HttpPost post;
HttpResponse response;
Context ctx;
public AsyncHandlerService() {
super("AsyncHandlerService");
ctx = this;
}
@Override
protected void onHandleIntent(Intent intent) {
new LoadDeviceInfo().execute();
}
class LoadDeviceInfo extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Updating device info...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); //Exception here..
}
protected String doInBackground(String... args) {
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
UPDATE:
I am calling the IntentService
in the broadcast receiver that has the intent filter of android.intent.action.PACKAGE_REPLACED
defined in android manifest. The code ---
public class OnUpgradeBroadcastReceiver extends BroadcastReceiver {
Context activity;
@Override
public void onReceive(final Context context, final Intent intent) {
activity = context;
Intent msgIntent = new Intent(activity, AsyncHandlerService.class);
activity.startService(msgIntent);
}
}
Error Log:
com.testapp.main fatal error : Unable to add window --
token null is not for an application
android.view.WindowManager$BadTokenException: Unable to add window --
token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:588)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.
addView(WindowManagerImpl.java:149)
at android.app.Dialog.show(Dialog.java:277)
at com.testapp.main.AsyncHandlerService$LoadDeviceInfo.
onPreExecute(AsyncHandlerService.java:62)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
First, IntentService
already uses a background thread. You do not need another background thread. Do the work that needs to be done in the background in onHandleIntent()
.
Second, a Service
cannot display a Dialog
. Instead, let the UI layer of your app know that the work was done via a message on an event bus (e.g., LocalBroadcastManager
, greenrobot's EventBus, Square's Otto). If the UI layer does not handle the event, your service can raise a Notification
or otherwise let the user know about the work that was done, if that is needed.