Android廣播基礎

來源:互聯網
上載者:User

標籤:get   adc   receiver   通訊   監聽   需求   XML   建立   lte   

廣播在Android中的作用相當於學校的喇叭。

廣播是一種跨進程的通訊方式,分為標準廣播和有序廣播。標準廣播是一種完全非同步廣播,這種廣播的效率比較高,同時也意味著不會被攔截;有序廣播則是一種完全同步的操作,廣播接收器在接收該類型廣播的時候是有序的,並且有權利攔截該廣播。

動態註冊:

1> 建立廣播接收類,繼承BroadcastReceiver,並重寫父類onReceive方法;

2> 監聽過濾器:

     IntentFilter intentFilter= new IntentFilter() ;

     intentFilter.setAction("android.net.conn.CONNECTIVITY_CHANGE");

     networkRecvice = new NetworkRecvice();

     registerReceiver(networkRecvice,intentFilter);

3> 登出廣播

     unregisteReceiver(networkRecvice);

靜態註冊:

      在AndroidManifest.xml中進行註冊:

       <receiver

         android:name= ".networkRecvice"

         <intent-filter>

             <action android:name="android.net.conn.CONNECTIVITY_CHANGE">

         <intent-filter>

        </receiver>

發送有序廣播:

      發送廣播:

            Intent intent = new Intent("android.net.conn.CONNECTIVITY_CHANGE");

            sendOrderedBroadcast(intent,null);

      設定優先權:       

     <receiver

         android:name= ".networkRecvice"

         <intent-filter android:priority="100">

             <action android:name="android.net.conn.CONNECTIVITY_CHANGE">

         <intent-filter>

      </receiver>

       攔截廣播:

         abortBroadcast();

使用本地廣播:

     以上所發送和接收的廣播全部屬於系統全域廣播,即發出的廣播可以被其他任何應用程式接收到,並且也可以接受來自其他任何程式的廣播。為瞭解決安全性喬恩題,Android引入了“本地廣播體制”。

     註冊和接收本地廣播與系統廣播區別不大,主要在於增加了使用LocalBroadcastManager來對廣播進行管理。

      發送:

          LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);

          .........

          manager.sendBroadcast(intent);

 

廣播的使用比較簡單,主要掌握其兩種不同的註冊方式,根據需求進行具體的應用。

Android廣播基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.