Android動態注冊廣播,發送和接受消息。


Android Activity傳值方式有多重,常見的有靜態類傳值,intent傳值,SharedPreferences,以及廣播傳值等方式。

 

接下來我在這里演示一下如何通過廣播發送數據,如何在activity中動態注冊,接受數據。


1,在項目中創建自定義廣播類 代碼如下。

 

public class AmosBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}




2,如何發送一個實體類的廣播? 

2.1 deviceMode為實體類,該類必須implements Serializable
public class DeviceMode implements Serializable {
public String str_Command;
public String getStr_Command() {
return str_Command;
}

public void setStr_Command(String str_Command) {
this.str_Command = str_Command;
}
 }

2.2 實例化后填充數據在需要發送數據的地方putExtra
Intent intent = new Intent();
intent.setAction("com.amos.demo");
intent.putExtra("deviceValue",deviceMode);
sendBroadcast(intent);



3,在activity中廣播的使用

3.1使用前先注冊
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.amos.demo");
registerReceiver(mReceiver,intentFilter);


3.2數據的接收和處理
private AmosBroadCastReceiver mReceiver = new AmosBroadCastReceiver() {
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if("com.amos.demo".equals(action))
{
DeviceMode deviceMode= (DeviceMode) intent.getSerializableExtra("deviceValue");
if(deviceMode!=null) {
int commandValue = Integer.parseInt(deviceMode.getStr_Command());
runOnUiThread(new Runnable() {
@Override
public void run() {
                //接收后的數據在線程更新UI
}
});
}
}
}
};


3.3 使用完畢后要注銷
unregisterReceiver(mReceiver); // 注銷廣播接收器

4,其他

廣播是可以一對多的,發送者不用管是否有接收者,在發送的時候intent.setAction("com.amos.demo"); 這個相當於廣播的標志或名稱,今后我們可以通過這個來辨別是誰發送出來的。

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM