天天看點

TabHost頁和子Activity之間的通訊

tabhost的各個tab頁,都是由activity組成。 

現在,某個子activity中處理資料後,要自動跳轉到另外一個tab頁中。這樣,需要有個tabhost頁和子activity之間的通訊的機制。 

子activity通知tabhost: 

1、通過廣播方式 

1)在tabhost中定義廣播 

定義變量 

protected messagebroadcastreceiver myreceiver = null; 

在oncreate中注冊: 

加入receivebroadcast(); 

private void receivebroadcast() { 

myreceiver = new messagebroadcastreceiver(); 

//log.d(log_tag, "receivebroadcast() ::::: " + myreceiver.hashcode()); 

intentfilter intentfilter = new intentfilter("android.intent.action.main"); 

registerreceiver(myreceiver, intentfilter); 

在ondestroy中釋放廣播 

if (myreceiver != null) 

unregisterreceiver(myreceiver); 

messagebroadcastreceiver類定義: 

public class messagebroadcastreceiver extends broadcastreceiver { 

@override 

public void onreceive(context context, intent intent) { 

try { 

string action = intent.getaction(); 

if (action.equals("android.intent.action.main")) { 

switch (intent.getintextra("msg", 0)) { 

case constant.broadcast_key_tabhost_change: { 

int tabindex = intent.getintextra("tabindex", 0); 

animatechangetab(tabindex); 

} catch (exception e) { 

e.printstacktrace(); 

log.v(log_tag, e.getmessage()); 

2)在子activity中調用 

intent intent = new intent("android.intent.action.main"); 

intent.putextra("msg", constant.broadcast_key_tabhost_change); 

intent.putextra("tabindex", 0); 

sendbroadcast(intent); 

2、通過handler接收消息 

1)在tabhost中定義handler 

// 得到主線程的looper對象 

looper looper = looper.mylooper(); 

// 這個myhandler由主線程建立是以它與主線程關聯 

public messagehandler msghandler = new messagehandler(looper); 

private void showmessage(string message) { 

// 發送本次資訊 

msghandler.removemessages(0); 

message m = msghandler.obtainmessage(1, 1, 1, message); // 構造要傳遞的消息 

msghandler.sendmessage(m); // 發送消息: 系統會自動調用handlemessage 方法來處理消息 

public class messagehandler extends handler { 

public messagehandler(looper looper) { 

super(looper); 

}                 

public void handlemessage(message msg) { // 處理消息 

switch (msg.what) { 

case constant.broadcast_key_tabhost_change: 

int tabindex = (integer) msg.obj; 

break; 

default: 

toast.maketext(getapplicationcontext(), msg.obj.tostring(), 

toast.length_short).show(); 

basketballmainactivity t= (basketballmainactivity) getparent();                  

message message = new message(); 

message.what = constant.broadcast_key_tabhost_change; 

message.obj  = 0; 

    t.msghandler.sendmessage(message);  

tabhost通知子activity: 

1、子activity是活動的 

在tabhost中增加 

activity currentactivity = getcurrentactivity(); 

if (currentactivity instanceof a) { 

           ((a) currentactivity).處理方法xxx; 

 } 

2、子activity是不是活動的 

在子activity的 

protected void onresume() { 

//添加邏輯即可 

}