android--廣播Broadcast【十三】

來源:互聯網
上載者:User

標籤:broadcastreceiver   broadcast   android   

廣播(Broadcast)是在組件之間傳播資料(Intent)的一種機制;這些組件甚至是可以位於不同的進程中,起到處理序間通訊的作用,主要是用於通知方面的.,下面要建立一個該例子的demo.

1.先定義一下通知廣播的訊息標識

private String MSG_BROADCAST = "MSG_BROADCAST";

2.廣播監聽以及處理廣播訊息

private void listen() {IntentFilter filter = new IntentFilter();filter.addAction(MSG_BROADCAST);MainActivity.this.registerReceiver(receiver, filter);}private BroadcastReceiver receiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (MSG_BROADCAST.equals(action)) {Log.i(TAG,"recv msg");}}};

3.廣播監聽停止

private void stopListen() {MainActivity.this.unregisterReceiver(receiver);}

4.分別在onResume和onPause事件裡面調用

@Overridepublic void onResume() {super.onResume();listen();}@Overridepublic void onPause() {super.onPause();stopListen();}

5.測試發廣播

btn = (Button) this.findViewById(R.id.button1);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG, "btn click start ");Intent intent = new Intent(MSG_BROADCAST);intent.putExtra("message", "test");// 參數sendBroadcast(intent);}});


android--廣播Broadcast【十三】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.