0

I want to change code in activity from service how can i do this. i want to put this code

button1.setBackgroundResource(R.drawable.play);

in my service code and change it in my activity

3 Answers3

1

You should use the LocalBroadcastManager to send an Intent from your service to your Activity.

Intent intent = new Intent("changeButtonColorEvent");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Then in your Activity, you register a Receiver and react on receiving the above Intent

@Override
public void onResume(Bundle savedInstanceState) {

 ...

 // Register to receive messages.
 LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
  new IntentFilter("changeButtonColorEvent"));
}

// Our handler for received Intents. 
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
  button1.setBackgroundResource(R.drawable.play);
 }
};

@Override
protected void onPause() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onDestroy();
}
Katerina A.
  • 1,268
  • 10
  • 24
0

A solution would be to use:

public class DummyActivity extends Activity
{
    public static DummyActivity instance = null;
    public Button btn = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        btn = (Button) findViewById(R.id.btn);

        // Do some operations here
    }

    @Override
    public void onResume()
    {
        super.onResume();
        instance = this;
    }

    @Override
    public void onPause()
    {
        super.onPause();
        instance = null;
    }
}

Then in your service, use

if (DummyActivity.instance != null) DummyActivity.instance.btn.setBackgroundResource(R.drawable.play);
Manitoba
  • 8,522
  • 11
  • 60
  • 122
  • 1
    NO! This is wrong... In this case you could do anything with your activity from anywhere in code. If you need something like this and you do not want to create BroadcastReceivers, you could use interfaces, but for that you'd have to think of a really good approach – Toochka Sep 17 '14 at 12:39
  • I didn't say it was a perfect solution. This is a just a working one. A better way would be to use `binders` (http://stackoverflow.com/questions/17513717/update-service-running-on-background) – Manitoba Sep 17 '14 at 12:44
0

Android has actually binders to communicate from the Activity to the Service, but nothing really is made for the other way around.

If you want to communicate from the Service to the Activity, I would suggest to use EventBus. It's the principle of a bus of events, where the Service can post on the bus and the activity can listen, and act upon events.

galex
  • 3,279
  • 2
  • 34
  • 46