NullPointer
NullPointer

Reputation: 89

Service can't control activity UI?

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.

Upvotes: 0

Views: 80

Answers (1)

Aadi Droid
Aadi Droid

Reputation: 1739

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.
    }
}

Upvotes: 1

Related Questions