两个Activity之间可以通过发送广播来控制另外一个activity的UI更新,比如团购APP里:我下了个订单之后,那么我可以通过发送广播通知“我的订单”里面的内容内容自动更新。
再重复一遍我遇到的问题,就是在MainActivity里面打开AnotherActivity去执行一些操作,相应的改变MainActivity里的一些布局或者执行一些动作,最开始想到的就是把MainActivity的Handler直接传给AnotherActivity,好像不可行,就有了这篇和上一篇文章。
上一篇方案一是通过重写application来在两个activity之间共享Handler的,今天这个方案是通过广播机制解决本来想要通过传递handler来实现的功能,算是Activity之间传递Handler问题的变通方案,
其实很简单,就是Broadcast的应用,替换了原来想要通过共享handler解决的思路。
代码如下
MainActivity:
package jason.broadcastinsteadofhanlderdemo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { TextView textView; Button sButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.show); sButton = (Button) findViewById(R.id.startAnother); sButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(MainActivity.this,AnotherActivity.class)); } }); IntentFilter filter = new IntentFilter(AnotherActivity.action); registerReceiver(broadcastReceiver, filter); } BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub textView.setText(intent.getExtras().getString("data")); } }; protected void onDestroy() { unregisterReceiver(broadcastReceiver); }; }
AnotherActivity:
package jason.broadcastinsteadofhanlderdemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AnotherActivity extends Activity { public static final String action = "jason.broadcast.action"; Button update; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.another); update = (Button) findViewById(R.id.updateMain); update.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(action); intent.putExtra("data", "yes i am data"); sendBroadcast(intent); finish(); } }); } }