I have a service that I have started from MainActivity with:
Intent intent = new Intent(getBaseContext(), MyService.class);
getBaseContext().startService(intent);
Inside MyService, I create and start a thread, giving it a reference to the Service's Context:
mThread = new MyThread(this);
mThread.start();
Then inside the thread, I want to display a ProgressDialog. I tried this:
mProgressDialog = ProgressDialog.show(mContext,
"", "Receiving file...", true);
mProgressDialog.show();
but I get "RuntimeException: Can't create handler inside thread that has not called Looper.prepare()". This makes sense, so I tried this instead:
HandlerThread progressHandlerThread = new HandlerThread(
"ProgressHandlerThread");
progressHandlerThread.start();
Handler progressHandler = new Handler(
progressHandlerThread.getLooper());
progressHandler.post(new Runnable()
{
@Override
public void run()
{
mProgressDialog = ProgressDialog.show(mContext, "",
"Receiving file...", true);
mProgressDialog.show();
}
});
but I get "BadTokenException: Unable to add window token is not for an application" but I don't understand what that error means.
I have seen this: Show ProgressDialog from thread inside the Service
and the conclusion seems to be that I need to runOnUIThread, but I don't have a reference to an Activity to do that since I am in a Service. Can anyone explain this BadTokenException and suggest a good way to do this?