Android studio 廣播的簡單使用代碼詳解
1.在布局文件里面加入按鈕,等會發(fā)送廣播
<?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"> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="發(fā)送廣播"></Button> </LinearLayout>
2.使用廣播的第一步當(dāng)然是創(chuàng)建一個廣播接受者
public class MyBrodestReciver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //判斷action是否為添加的action,如果是則toast String action = intent.getAction(); if (action.equals("one_brodest")){ Toast.makeText(context, "發(fā)送了一個廣播", Toast.LENGTH_SHORT).show(); } } }
3.創(chuàng)建完廣播接受者以后注冊廣播,并且添加一個action
//新建intentFilter對象 通過addAction添加廣播 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("one_brodest");
4.然后注冊一個廣播
//注冊廣播 MyBrodestReciver myBrodestReciver = new MyBrodestReciver(); registerReceiver(myBrodestReciver,intentFilter);
5.到這里廣播的注冊已經(jīng)完成接下來就是使用了
//做一個點擊事件發(fā)送一個廣播 send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction("one_brodest"); sendBroadcast(intent); } });
6.這就是點擊之后的效果,成功發(fā)送了一個廣播?。。。。。。。。。。。。。?!
7.最后一步,銷毀廣播
@Override protected void onDestroy() { super.onDestroy(); //銷毀廣播 unregisterReceiver(brodestReciver); }
到此這篇關(guān)于Android studio 廣播的簡單使用的文章就介紹到這了,更多相關(guān)Android studio 廣播內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android無障礙自動化結(jié)合opencv實現(xiàn)支付寶能量自動收集操作方法
opencv可以進行圖像識別,兩者結(jié)合在一起即可實現(xiàn)支付寶能量自動收集,opencv用于識別能量,無障礙服務(wù)用于模擬手勢,即點擊能量,這篇文章主要介紹了Android無障礙自動化結(jié)合opencv實現(xiàn)支付寶能量自動收集,需要的朋友可以參考下2024-07-07Android 自定義精美界面包含選項菜單 上下文菜單及監(jiān)聽詳解流程
這篇文章主要介紹了一個Android實例小項目,它包含了選項菜單、上下文菜單及其對應(yīng)的監(jiān)聽事件,它很小,但這部分功能在Android開發(fā)中很常見,需要的朋友來看看吧2021-11-11Android AIDL中Map參數(shù)傳遞的問題詳解
這篇文章主要給大家介紹了關(guān)于Android AIDL中Map參數(shù)傳遞問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友下面來一起看看吧。2017-12-12詳解RxJava2 Retrofit2 網(wǎng)絡(luò)框架簡潔輕便封裝
本篇文章主要介紹了詳解RxJava2 Retrofit2 網(wǎng)絡(luò)框架簡潔輕便封裝,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Android用戶輸入自動提示控件AutoCompleteTextView使用方法
這篇文章主要為大家詳細(xì)介紹了Android用戶輸入自動提示控件AutoCompleteTextView的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08Android 通過ViewHolder優(yōu)化適配器的實現(xiàn)方法(必看)
下面小編就為大家?guī)硪黄狝ndroid 通過ViewHolder優(yōu)化適配器的實現(xiàn)方法(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04Android中使用PopupWindow 仿微信點贊和評論彈出
微信朋友圈的點贊和評論功能,有2個組成部分:左下角的“更多”按鈕;點擊該按鈕后彈出的對話框。這篇文章主要介紹了Android中使用PopupWindow 仿微信點贊和評論彈出,需要的朋友可以參考下2017-04-04