在應用程序中發送廣播比較簡單。只須要調用sendBroadcast方法便可,該方法須要一個Intent對象,經過Intent對象能夠發送須要廣播的數據。java
/ 經過Intent類的構造方法指定廣播的ID Intent intent = new Intent("net.blogjava.mobile.MYBROADCAST"); // 將要廣播的數據添加到Intent對象中 intent.putExtra("text", editText.getText().toString()); // 發送廣播 sendBroadcast(intent);
發送廣播並不須要在AndroidManifest.xml文件中註冊,但接收廣播必須在AndroidManifest.xml文件中註冊 receiver。android
java類ide
package net.blogjava.mobile.receiver; ... ... public class MyReceiver extends BroadcastReceiver { // 當sendbroadcast發送廣播時,系統會調用onReceive方法來接收廣播 @Override public void onReceive(Context context, Intent intent) { // 判斷是否爲sendbroadcast發送的廣播 if ("net.blogjava.mobile.MYBROADCAST".equals(intent.getAction())) { Bundle bundle = intent.getExtras(); if (bundle != null) { String text = bundle.getString("text"); Toast.makeText(context, "成功接收廣播:" + text, Toast.LENGTH_LONG).show(); } } } }
_ 在AndroidManifest.xml文件中註冊receiver_code
<!-- 註冊receiver <receiver android:name="MyReceiver"> <intent-filter> <action android:name="net.blogjava.mobile.MYBROADCAST" /> </intent-filter> </receiver>