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
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
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();
}
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);
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.