Android studio 廣播的簡單使用代碼詳解
1.在布局文件里面加入按鈕,等會發送廣播
<?xml version='1.0' encoding='utf-8'?><LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:app='http://schemas.android.com/apk/res-auto' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:gravity='center' tools:context='.MainActivity3'><Buttonandroid: android:layout_width='wrap_content'android:layout_height='wrap_content'android:text='發送廣播'></Button></LinearLayout>
2.使用廣播的第一步當然是創建一個廣播接受者
public class MyBrodestReciver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) { //判斷action是否為添加的action,如果是則toast String action = intent.getAction(); if (action.equals('one_brodest')){Toast.makeText(context, '發送了一個廣播', Toast.LENGTH_SHORT).show(); }} }
3.創建完廣播接受者以后注冊廣播,并且添加一個action
//新建intentFilter對象 通過addAction添加廣播 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction('one_brodest');
4.然后注冊一個廣播
//注冊廣播 MyBrodestReciver myBrodestReciver = new MyBrodestReciver(); registerReceiver(myBrodestReciver,intentFilter);
5.到這里廣播的注冊已經完成接下來就是使用了
//做一個點擊事件發送一個廣播 send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction('one_brodest'); sendBroadcast(intent); } });
6.這就是點擊之后的效果,成功發送了一個廣播?。。。。。。。。。。。。。?!
7.最后一步,銷毀廣播
@Override protected void onDestroy() {super.onDestroy();//銷毀廣播unregisterReceiver(brodestReciver); }
到此這篇關于Android studio 廣播的簡單使用的文章就介紹到這了,更多相關Android studio 廣播內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. 解決python腳本中error: unrecognized arguments: True錯誤2. Python使用jupyter notebook查看ipynb文件過程解析3. php的curl攜帶header請求頭信息實現http訪問的方法4. php網絡安全中命令執行漏洞的產生及本質探究5. IntelliJ IDEA創建普通的Java 項目及創建 Java 文件并運行的教程6. ajax請求添加自定義header參數代碼7. python利用os模塊編寫文件復制功能——copy()函數用法8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. php測試程序運行速度和頁面執行速度的代碼10. 解決Python 進程池Pool中一些坑
