lisovaccaro
lisovaccaro

Reputation: 33996

FindViewById in a class type Service?

I'm working with the sample media player given by the android sdk. MainActivity starts Service MusicService with startService(new Intent(MusicService.ACTION_PLAY)).

I need to find a view by ID inside the Service but I don't know how to do it:

    findViewById(R.id.playbutton).setVisibility(View.GONE);

I've found some similar questions but none provide a simple solution (the most similar question's accepted answer is actually "no you can't" and I'm sure it's possible). How can I make this line work inside the Service? Do I have to pass the context from MainActivity to it, how do I do it?

Upvotes: 0

Views: 1063

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007474

Since the service handles media playback the interface should be updated directly before playing/pausing that's why I need to update the ui from it

No, you do not. You need to let the UI know, if it exists, about the state change. The UI will affect its own changes how it sees fit. There may not be any UI at all, depending upon what the user has done.

For letting any affected bits of UI know about the state change, you can:

  • send a regular broadcast Intent, or
  • use LocalBroadcastManager to send a "narrowcast" Intent (works a lot like a broadcast, but it is completely within your process), or
  • use Otto as an event bus

Upvotes: 2

Related Questions