handler,registerReceiver以及activty和BroadcastReceiver的传值

public class Container extends TabActivity{

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

		host = getTabHost();
		Intent intent = new Intent(this, Tab1Activity.class);
		host.addTab(host.newTabSpec("one").setIndicator("TAB1").setContent(intent));
		intent = new Intent(this, Tab2Activity.class);
		host.addTab(host.newTabSpec("two").setIndicator("TAB2").setContent(intent));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		receiver = new TabChangeReceiver();
		registerReceiver(receiver, new IntentFilter("com.novoda.TAB"), null, mHandler);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	};
	
    protected Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
            	case SWITCH_TAB:
            		Log.i("handler", "using the handler");
                    host.setCurrentTab(msg.arg1);            		
            		break;
            }
        }
    };

    public class TabChangeReceiver extends android.content.BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			int intExtra = intent.getIntExtra("tab", 0);
			Log.i(TabChangeReceiver.class.getSimpleName(), "Recieved broadcast with extra=[" + intExtra + "]");
			
			mHandler.sendMessage(mHandler.obtainMessage(SWITCH_TAB, intExtra, 0));
		}
	}
	
	private TabHost host;
	public static final int SWITCH_TAB = 2545;
	protected static TabChangeReceiver receiver;
	
}

 

public class Tab1Activity extends Activity{
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.tab1);
        findViewById(R.id.tab1button).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("com.novoda.TAB");
				intent.putExtra("tab", 1);
				sendBroadcast(intent);
			}
		});
	}
}

 

public class Tab2Activity extends Activity{
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.tab2);
        findViewById(R.id.tab2button).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("com.novoda.TAB");
				intent.putExtra("tab", 0);
				sendBroadcast(intent);
			}
		});        
	}
}

 

这个传值是通过setbroadcast监听实现的,这个主要用来监听 同一个类型的activityIntent intent = new Intent("com.novoda.TAB");
比较好,这里呢也使用handler处理监听到的消息

你可能感兴趣的:(android)