Android_Broadcast

靜態(tài)和動(dòng)態(tài)兩種注冊方法:

  • 靜態(tài)注冊, 在AndroidManifest.xml中加上<Receiver>標(biāo)簽。
  • 動(dòng)態(tài)注冊, 通過 Context.registerReceiver()方法進(jìn)行注冊。比如在onResume中注冊,在onPause中注銷。
public class MyReceiver extends BroadcastReceiver{ 
public MyReceiver() { 
super(); 
Log.d(AppConstants.LOG_TAG, "Receiver constructor"); 
} 
@Override 
public void onReceive(Context context, Intent intent) {        
Log.d(AppConstants.LOG_TAG, "onReceive"); 
String message = intent.getStringExtra("msg");    
Log.i(AppConstants.LOG_TAG, message);  
Toast.makeText(context, "Received! msg: " + message, Toast.LENGTH_SHORT).show(); 
}
}

發(fā)送廣播

public static final String BROADCAST_ACTION ="com.example.demobroadcast.BroadcastAction";
Intent intent = new Intent();     
intent.setAction(BROADCAST_ACTION);   
intent.putExtra("msg", "發(fā)送廣播"); 
sendBroadcast(intent);

動(dòng)態(tài)注冊

@Override protected void onResume() { 
super.onResume(); 
mReceiver = new MyReceiver(); 
IntentFilter intentFilter= new   
IntentFilter(BROADCAST_ACTION); registerReceiver(mReceiver,  
intentFilter); 
} 
@Override protected void onPause() { 
super.onPause(); 
unregisterReceiver(mReceiver); 
}

靜態(tài)注冊

<receiver
        android:name="com.example.demobroadcast.MyReceiver">
        <intent-filter  >
            <action android:name="com.example.demobroadcast.BroadcastAction" />
        </intent-filter>
    </receiver>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Broadcast概述 該部分內(nèi)容主要翻譯自Google Android Developers文檔 Android...
    lbtrace閱讀 2,267評論 0 2
  • 前言:本文所寫的是博主的個(gè)人見解,如有錯(cuò)誤或者不恰當(dāng)之處,歡迎私信博主,加以改正! 原文鏈接,demo鏈接 廣播簡...
    PassersHowe閱讀 3,564評論 0 9
  • 參考承香墨影的兩篇博客Android--廣播BroadcastReceiverAndroid--攔截系統(tǒng)Broad...
    合肥黑閱讀 2,123評論 2 11
  • 轉(zhuǎn)自Android四大基本組件介紹與生命周期Android四大基本組件分別是Activity,Service服務(wù),...
    開子的私家地閱讀 1,573評論 0 5
  • 面試題總結(jié) 通用 安卓學(xué)習(xí)途徑, 尋找資料學(xué)習(xí)的博客網(wǎng)站 AndroidStudio使用, 插件使用 安卓和蘋果的...
    JingBeibei閱讀 1,864評論 2 21

友情鏈接更多精彩內(nèi)容