0

I have problem when I control Activity UI from service. It doesn't work.

class MainActivity

public void showNotice() {
    Log.d("log", "can't connect to server");
    tvText.setText(notice);
    tvTex.setVisibility(View.VISIBLE);
    pbDialog.hide();
}

I call showNotice method in my service:

((MainActivity) mContext).showNotice();

But it only show log "can't connect to server".

tvText doesn't change anything, not change text, not visible. pbDialog does'n hide?

Can i help me resolve it? Many thanks.

NullPointer
  • 89
  • 1
  • 7
  • 1
    Try to set showNotice() as a static method from your MainActivity, and then in your service call MainActivity.showNotice() to see if works... – tibuurcio Oct 06 '14 at 03:41
  • Try using broadcast , You can find the details in below link http://stackoverflow.com/questions/14695537/android-update-activity-ui-from-service – Ranjithkumar Oct 06 '14 at 03:44

1 Answers1

1

A service runs in its own background thread, the UI can be modified only from the UI Thread which is pretty much with the main activity.

You can try doing this, you can broadcast an event from the service when you want to hide the dialog box. Have a broadcast listener registered for this which would handle the UI modification. You should probably be using a LocalBroadcastManager and give your broadcast a unique name.

In your mainActivity, use

registerReceiver(<receiver instance>, <broadcast name>)

in the onStart or onCreate method.

This will setup your mainActivity to listen to the broadcasts, next you need to define your broadcast receiver which is the in the above register call.

BroadcastReceiver receiver;
receiver = new BroadcastReceiver() {
    public void onReceive(Context c, Intent i) {
        //Modify the UI, in this case hide the dialog box.
    }
}
Aadi Droid
  • 1,689
  • 4
  • 22
  • 46