標籤:android blog io ar os sp java on 檔案
1.
2. 實現代碼
layout.xml
<Button android:id="@+id/testBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" />
MainActivity.java
public static final String MY_ACTION = "iflab.test.MY_ACTION"; // 自訂ACTIONprivate Button testBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);testBtn = (Button) findViewById(R.id.testBtn);testBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent();intent.setAction(MY_ACTION);intent.putExtra("message", "來自於廣播的訊息!"); // 設定廣播的訊息sendBroadcast(intent);}});}
testBroadcastReceiver.java
public class testBroadcastReceiver extends BroadcastReceiver {// context 內容物件 intent 接收的意圖對象@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString str;str = "接收到的廣播訊息為:" + intent.getStringExtra("message"); // 接收訊息Toast.makeText(context, str, Toast.LENGTH_SHORT).show();}}
設定檔中需要填寫的資訊
<receiver android:name="testBroadcastReceiver" > <intent-filter> <action android:name="iflab.test.MY_ACTION" /> </intent-filter> </receiver>
3. 說明
<action android:name="iflab.test.MY_ACTION" /> 為你在 MainActivity 中定義的常量
<receiver android:name="testBroadcastReceiver" > name 的值為 你要接收廣播的時候所啟動的類 testBroadcastReceiver
Android -- 簡單廣播接收與發送(1)