我正在尝试读取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);
我想要实现的目标:我想将TextView
中MainActivity
的文字设置为message
字符串。我该怎么做才能实现这个目标?
答案 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
中注册BoadcastReceiverregisterReceiver(updTextViewReceiver, new IntentFilter(EXTRA_MESSAGE));
取消注册onPause中的BoadcastReceiver
unregisterReceiver(updTextViewReceiver);
完成!