我想从服务中更改活动中的代码 我怎样才能做到这一点。 我想把这段代码
button1.setBackgroundResource(R.drawable.play);
在我的服务代码中,并在我的活动中更改
答案 0 :(得分:1)
您应该使用LocalBroadcastManager将您的服务中的Intent发送到您的Activity。
Intent intent = new Intent("changeButtonColorEvent");
LocalBroadcastManager.getInstance(this).sendBroadcast(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();
}
答案 1 :(得分:0)
解决方案是使用:
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;
}
}
然后在您的服务中,使用
if (DummyActivity.instance != null) DummyActivity.instance.btn.setBackgroundResource(R.drawable.play);
答案 2 :(得分:0)