Get Exception when showing Alert Dialog from Service.
Following is the code in my Service class: I am trying to show an AlertDialog.
But I get the error: Una
You should keep some of the things in your mind while creating your gui:
All time consuming non gui work should be done in background (using asyncTask, Services, Threads etc).
GUI(like views and other graphical objects) should always be created and updated from UIthreads.
So create and displaying dialog is a UI work so it should be in UI thread. To run any code in UI thread you can use different methods like:
I think for your case runOnUiThread is best So use
runOnUiThread (new Runnable() {
public void run ()
{
// WRITE YOUR PIECE OF CODE HERE TO UPDATE OR CREATE GUI.
}
});
To understand the concept this can help you:
http://developer.android.com/guide/components/processes-and-threads.html
To create broadcast you can use:
Step 1: Create a broadcast receiver in your activity from where you are starting your service.
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("create_dialog")) {
// create your dialog here.
}
}
};
Step 2: Register your receiver after creating your broadcast receiver.
IntentFilter filter = new IntentFilter("create_dialog");
registerReceiver(receiver, filter);
Step 3: Send broadcast from your service to display dialog.
Intent intent = new Intent("create_dialog");
intent.putExtra("dialog_data", data_object to display in dialog);
SendBroadcast(intent);
I hope this can help you.