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)完成接下來就是使用了
//做一個點(diǎn)擊事件發(fā)送一個廣播
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("one_brodest");
sendBroadcast(intent);
}
});
6.這就是點(diǎn)擊之后的效果,成功發(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?ViewPager你可能不知道的刷新操作分享
這篇文章主要為大家詳細(xì)介紹了Android中ViewPager你可能不知道的刷新操作,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,需要的可以參考一下2023-05-05
安卓(Android)中如何實(shí)現(xiàn)滑動導(dǎo)航
導(dǎo)航是移動應(yīng)用最重要的方面之一,對用戶體驗(yàn)是良好還是糟糕起著至關(guān)重要的作用。好的導(dǎo)航可以讓一款應(yīng)用更加易用并且讓用戶快速上手。相反,糟糕的應(yīng)用導(dǎo)航很容易讓人討厭,并遭到用戶的拋棄。2014-08-08
淺析Android手機(jī)衛(wèi)士自定義控件的屬性
這篇文章主要介紹了淺析Android手機(jī)衛(wèi)士自定義控件的屬性,本文介紹的非常詳細(xì)具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧2016-04-04
Android利用GridView實(shí)現(xiàn)單選功能
這篇文章主要為大家詳細(xì)介紹了Android利用GridView實(shí)現(xiàn)單選功能的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
Flutter Flar動畫使用實(shí)戰(zhàn)示例
這篇文章主要為大家介紹了Flutter Flar動畫使用實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
Android 幾種屏幕間跳轉(zhuǎn)的跳轉(zhuǎn)Intent Bundle
這篇文章主要介紹了Android 幾種屏幕間跳轉(zhuǎn)的跳轉(zhuǎn)Intent Bundle,有需要的朋友可以參考一下2013-12-12
Android Studio實(shí)現(xiàn)下拉列表效果
這篇文章主要為大家詳細(xì)介紹了Android Studio實(shí)現(xiàn)下拉列表效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
Android 解決WebView多進(jìn)程崩潰的方法
這篇文章主要介紹了Android 解決WebView多進(jìn)程崩潰的方法,幫助大家更好的理解和學(xué)習(xí)使用Android開發(fā),感興趣的朋友可以了解下2021-03-03

