MainActivity如下:
package cc.testbroadcasta; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; /** * Demo描述: * 在代碼中註冊廣播接收者 * 1 在onCreate()中註冊廣播接收者 * 2 在onDestroy()中取消註冊廣播接收者 */ public class MainActivity extends Activity { private BroadcastReceiverTest mBroadcastReceiverTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //註冊一個廣播接收者 registerAReceiver(); //發送一個廣播 sendABroadcast(); } private void registerAReceiver(){ mBroadcastReceiverTest=new BroadcastReceiverTest(); //為廣播接收者設置IntentFilter IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("cc.test"); registerReceiver(mBroadcastReceiverTest, intentFilter); } private void sendABroadcast(){ Intent intent = new Intent(); // 設置Action intent.setAction("cc.test"); // 攜帶數據 intent.putExtra("name", "周星馳"); intent.putExtra("number", 9527); // 發送廣播 sendBroadcast(intent); } @Override protected void onDestroy() { super.onDestroy(); //取消廣播接收者的註冊 if (mBroadcastReceiverTest!=null) { unregisterReceiver(mBroadcastReceiverTest); } } }
BroadcastReceiverTest如下:
package cc.testbroadcasta; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BroadcastReceiverTest extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String name=intent.getStringExtra("name"); int number=intent.getIntExtra("number", 0); System.out.println("接收到廣播 name="+name+",number="+number); } public static void main(String[] args) { } }
main.xml如下: