Android studio 廣播的簡(jiǎn)單使用代碼詳解
1.在布局文件里面加入按鈕,等會(huì)發(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'><Buttonandroid: android:layout_width='wrap_content'android:layout_height='wrap_content'android:text='發(fā)送廣播'></Button></LinearLayout>
2.使用廣播的第一步當(dāng)然是創(chuàng)建一個(gè)廣播接受者
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, '發(fā)送了一個(gè)廣播', Toast.LENGTH_SHORT).show(); }} }
3.創(chuàng)建完廣播接受者以后注冊(cè)廣播,并且添加一個(gè)action
//新建intentFilter對(duì)象 通過addAction添加廣播 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction('one_brodest');
4.然后注冊(cè)一個(gè)廣播
//注冊(cè)廣播 MyBrodestReciver myBrodestReciver = new MyBrodestReciver(); registerReceiver(myBrodestReciver,intentFilter);
5.到這里廣播的注冊(cè)已經(jīng)完成接下來就是使用了
//做一個(gè)點(diǎn)擊事件發(fā)送一個(gè)廣播 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ā)送了一個(gè)廣播!!!!!!!!!!!!!!!

7.最后一步,銷毀廣播
@Override protected void onDestroy() {super.onDestroy();//銷毀廣播unregisterReceiver(brodestReciver); }
到此這篇關(guān)于Android studio 廣播的簡(jiǎn)單使用的文章就介紹到這了,更多相關(guān)Android studio 廣播內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 編程語言PHP在Web開發(fā)領(lǐng)域的優(yōu)勢(shì)在哪?3. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)4. Android如何加載Base64編碼格式圖片5. 什么是python的自省6. 解決Android studio xml界面無法預(yù)覽問題7. 基于android studio的layout的xml文件的創(chuàng)建方式8. 圖文詳解vue中proto文件的函數(shù)調(diào)用9. Vuex localStorage的具體使用10. 在IDEA中實(shí)現(xiàn)同時(shí)運(yùn)行2個(gè)相同的java程序

網(wǎng)公網(wǎng)安備