从sendBroadcast()接收数据

时间:2013-12-06 18:56:43

标签: java android android-intent

我正在尝试读取sendBroadcast()方法所携带的数据。我已经编写了此代码,并希望在message

中提供TextView
message = incoming.readUTF();
String[] incomingTable = new String[5];
incomingTable[0] = message;
incomingTable[1] = message;
Intent actual = new Intent(EXTRA_MESSAGE);
actual.putExtra("Message", String.format("%s", incomingTable[1]));
getBaseContext().sendBroadcast(actual);

我想要实现的目标:我想将TextViewMainActivity的文字设置为message字符串。我该怎么做才能实现这个目标?

1 个答案:

答案 0 :(得分:0)

在MainActivity中声明并定义broadcatReceiver:

UpdTextViewReceiver updTextViewReceiver;
public class UpdTextViewReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(action.equalsIgnoreCase(EXTRA_MESSAGE)){  
            String message = intent.getStringExtra("Message")
            MainActivity.updateTextView(message);
        }
   }

}  

private void updateTextView(String message){

    //Update the TextView here
}

在onCreate中实例化接收器:

updTextViewReceiver = new UpdTextViewReceiver();

在onResume

中注册BoadcastReceiver
registerReceiver(updTextViewReceiver, new IntentFilter(EXTRA_MESSAGE));  

取消注册onPause中的BoadcastReceiver

unregisterReceiver(updTextViewReceiver);  

完成!