Android 第二十課 廣播機制(大喇叭)----發送自定義廣播(包括發送標準廣播和發送有序廣播)

廣播分為兩種類型:標準廣播和有序廣播

我們來看一下具體這兩者的具體區別:

1、發送標準廣播

我們需要先定義一個廣播接收器來準備接收此廣播才行,否則也是白發。

新建一個MyBroadcastReceiver,代碼如下:

package com.example.broadcasttest;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;/*** Created by ZHJ on 2018/3/11.*/public class MyBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show();}
}

這里當MyBroadcastReceiver收到自定義的廣播時,就會彈出“received in MyBroadcastReceiver ”的提示。然后在AndroidManifest.xml中對這個廣播接收器進行修改:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.broadcasttest"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name = "android.permision.RECEIVE_BOOT_COMPLETED"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiver android:name=".MyBroadcastReceiver"android:enabled="true"android:exported="true"><intent-filter>   <action android:name="com.example.broadcasttest.MY_BROADCAST"/></intent-filter></receiver></application></manifest>

可以看到,這里讓MyBroadcastReceiver接收一條值為com.example.broadcasttest.MY_BROADCAST的廣播,因此待會在發送廣播的時候,我們就需要發出這樣的一條廣播。

修改activity_main.xml中的代碼,如下:

<?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"tools:context="com.example.broadcasttest.MainActivity"><Buttonandroid:id="@+id/button"android:layout_width="match_parent"android:layout_height="wrap_content" android:text="Send Broadcast"/></LinearLayout>

我們在布局中添加了一個按鈕,用于作為發送廣播的觸發點。

然后修改MainActivity中的代碼:

package com.example.broadcasttest;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private IntentFilter intentfiletr;private NetworkChangeReceiver networkChangeReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);....
????????  Button button = (Button)findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");sendBroadcast(intent);}});}....
}
可以看到,我們在按鈕的點擊事件里面加入了發送自定義廣播的邏輯,首先構建出了一個Intent對象,并把要發送的廣播的值傳入,然后調用了Context的sendBroadcast()方法將廣播發送出去,這樣監聽com.example.broadcasttest.MY_BROADCAST這條廣播的廣播接收器會收到消息。此時發出去的廣播就是一條標準廣播。

運行程序,點擊按鈕。

回顧如何發送一條標準廣播,首先你得有個廣播接收器,那我們就新建一個廣播接收器MyBroadcastReceiver,然后在里面添加一個Toast,用于接收后廣播用于反饋,但是我們要在AndroidManifest.xml文件中對這個廣播接收器進行修改,你要接收什么樣得廣播。廣播接收器就差不多做好了。我們開始準備發送廣播,添加一個按鈕,作為觸發點,在按鈕的點擊事件中,添加發送自定義廣播的邏輯。首先肯定要構建出Intent對象,把要發送的廣播的值傳入,然后調用Context的sendBroadcast()方法將廣播發送出去。這樣所有監聽com.example.broadcasttest.MY_BROADCAST這條廣播的廣播接收器就會收到消息。這就是一條標準廣播。

另外,廣播是使用Intent進行傳遞的,因此你還可以在Intent中攜帶一些數據傳遞給廣播接收器。

2、發送有序廣播

廣播是一種跨進程的通信方式,我們在應用程序內發出去的廣播,其他應用程序也是可以接收的。廢話不說,我們要驗證,

新建BroadcastTest2項目。當然我們還需要在這個項目中新建一個廣播接收器,用于接收上一次的自定義廣播,

新建AnotherBroadcastReceiver,代碼如下:

package com.example.broadcasttest2;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;/*** Created by ZHJ on 2018/3/11.*/public class AnotherBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context,"received AnotherBroadcastReceiver",Toast.LENGTH_SHORT).show();}
}

我們仍然是在廣播接收器的onReceive()方法中彈出了一段文本信息。然后,AndroidManifest.xml中對這個廣播接收器進行修改,代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.broadcasttest2"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiver android:name=".AnotherBroadcastReceiver"><intent-filter><action android:name="com.example.broadcasttest.MY_BROADCAST"/></intent-filter></receiver></application></manifest>

可以看到,AndroidBroadcastReceiver接收的仍然是com.example.broadcasttest.MY_BROADCAST這條廣播,把BroadcastTest2運行起來,點擊BroadcastTest1的按鈕,那么你會接收兩條提示信息。

這就證明了,我們的應用程序是可以被其他的應用程序接收到的。

發送有序廣播:

到現在為止,我們程序中發送的都是標準廣播,接下來,我們來發送有序廣播,重新回到Broadcast項目,然后修改MainActivity中的代碼,如下所示:

package com.example.broadcasttest;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private IntentFilter intentfiletr;private NetworkChangeReceiver networkChangeReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);intentfiletr = new IntentFilter();intentfiletr.addAction("android.net.conn.CONNECTIVITY_CHANGE");networkChangeReceiver = new NetworkChangeReceiver();registerReceiver(networkChangeReceiver,intentfiletr);Button button = (Button)findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");//注意這里的值一定要和BroadCastTest中的一樣。sendOrderedBroadcast(intent,null);//這里由sendBroadcast()方法變化。}});}........
}

只是將sendBroadcast()方法改成sendOrderBroadcast()方法,sendOrderBroadcast()方法接收兩個參數,第一個參數仍然是Intent,第二個參數是一個與權限相關的字符串,這里傳入null就行了。重新運行程序,這兩個應用程序仍然可以接收到這條廣播。


但是這時候的廣播接收器是有先后順序的,而且前面的廣播接收器還可以將廣播截斷,以阻止其傳播。

那么該如何設定廣播接收器的先后順序呢?當然是在注冊的時候進行設定的,修改AndroidManifest.xml中的代碼:

如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.broadcasttest"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name = "android.permision.RECEIVE_BOOT_COMPLETED"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiverandroid:name=".MyBroadcastReceiver"android:enabled="true"android:exported="true"><intent-filter android:priority="100">//我們給廣播接收器設置了優先級<action android:name="com.example.broadcasttest.MY_BROADCAST"/></intent-filter></receiver></application></manifest>

可以看到我們通過android:priority屬性給廣播接收器設置了優先級,優先級高的廣播接收器就可以先收到廣播,這里將MyBroadcastReceiver的優先級設成100,以保證它一定會在AnotherBroadcastReceicer之前收到廣播。

既然我們已經獲得了接收廣播的優先權,那么MyBroadCastReceiver就可以選擇時候允許廣播繼續傳遞了。

修該MyBroadcastReceiver中的代碼,如下:

package com.example.broadcasttest;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;/*** Created by ZHJ on 2018/3/11.*/public class MyBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show(); abortBroadcast();//調用abortBroadcast()方法。}
}

如果在onReceive()方法中調用了abortBroadcast()方法,就表示這條廣播截斷,優先級的廣播接收器就無法收到這條廣播。

重新運行程序。

只有MyBroadcastReceiver中的廣播接收器的Toast信息框可以彈出。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/274082.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/274082.shtml
英文地址,請注明出處:http://en.pswp.cn/news/274082.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

八大排序算法

概述 排序有內部排序和外部排序&#xff0c;內部排序是數據記錄在內存中進行排序&#xff0c;而外部排序是因排序的數據很大&#xff0c;一次不能容納全部的排序記錄&#xff0c;在排序過程中需要訪問外存。 我們這里說說八大排序就是內部排序。 當n較大&#xff0c;則應采用…

需求?

1 需求怎樣描述清楚&#xff1f; 利用用例技術&#xff0c;一般這里指的是系統用例&#xff1b;包括以下幾個內容&#xff1a; 用例視圖 系統的功能描述&#xff1b; 用例規約 規定了用戶和系統的交互過程&#xff1b;用戶如何使用系統&#xff1b;用戶如何交互&#xff0c;以及…

Android 第二十一課 RecyclerView簡單的應用之編寫“精美”的聊天頁面

1、由于我們會使用到RecyclerView&#xff0c;因此首先需要在app/build.gradle當中添加依賴庫。如下&#xff1a; apply plugin: com.android.application .... dependencies {....compile com.android.support:recyclerview-v7:26.1.0 } 2、然后開始編寫主頁面&#xff0c;修該…

VS 2008 生成操作中各個選項的差別

近日&#xff0c;在編譯C#項目時經常發現有些時候明明代碼沒錯&#xff0c;但就是編譯不過&#xff0c;只有選擇重新編譯或者清理再編譯才會不出錯&#xff0c;本著求學的態度&#xff0c;搜羅了下VS2008IDE中生成操作的種類以及差別&#xff0c;整理如下&#xff1a;內容(Cont…

dbus-python指南

菜鳥學dbus-python&#xff0c;翻譯dbus-python指南&#xff0c;錯誤之處請在所難免&#xff0c;請諸位不吝賜教&#xff0c;多多指正&#xff01;查看英文原版請點這里。 連接總線Connecting to the Bus方法調用Making method calls代理對象proxy objects接口和方法Interfaces…

JavaScript 第三課 DOM

主要內容&#xff1a; 節點5個常用的DOM方法&#xff1a;getElementById、getElementByTagname、getElementByClassName、getAttribute和setAttribute詳細內容: 1、文檔&#xff1a;DOM中的“D”如果沒有document(文檔),DOM也就無從談起。當創建了一個網頁并把它加載到Web瀏覽器…

源碼編譯安裝Nginx

1.源碼下載 Nginx在github上有一個只讀源碼庫&#xff0c;我獲取的源碼方式為&#xff1a; git clone https://github.com/nginx/nginx.git 2.configure 我下載源碼的時候&#xff0c;github上的源碼的目錄結構為: auto, conf, contrib, docs, misc, src共6個目錄。src目錄是…

SOAP協議初級指南(2)

目前的技術存在的問題&#xff1f;   盡管DCOM和IIOP都是固定的協議&#xff0c;業界還沒有完全轉向其中任何一個協議。沒有融合的部分原因是文化的問題所致。而且在當一些組織試圖標準化一個或另一個協議的時候&#xff0c;兩個協議的技術適用性就被提出質疑。傳統上認為DC…

JavaScript 第四課 案例研究:JavaScript圖片庫

主要內容&#xff1a;編寫一個優秀的標記文件編寫一個JavaScript函數以顯示用戶想要查看的內容由標記出發函數調用使用幾個新方法擴展這個JavaScript函數 學習過DOM&#xff0c;我們用JavaScript和DOM去建立一個圖片庫。最好的辦法是什么呢&#xff1f; 利用JavaScript來建立圖…

windows下mongodb安裝與使用整理

一、首先安裝mongodb 1.下載地址&#xff1a;http://www.mongodb.org/downloads 2.解壓縮到自己想要安裝的目錄&#xff0c;比如d:\mongodb 3.創建文件夾d:\mongodb\data\db、d:\mongodb\data\log&#xff0c;分別用來安裝db和日志文件&#xff0c;在log文件夾下創建一個日志文…

可變參數列表(va_list,va_arg,va_copy,va_start,va_end)

本文轉自:http://blog.csdn.net/costa100/article/details/5787068 va_list arg_ptr&#xff1a;定義一個指向個數可變的參數列表指針&#xff1b;      va_start(arg_ptr, argN)&#xff1a;使參數列表指針arg_ptr指向函數參數列表中的第一個可選參數&#xff0c;說明&…

src與href屬性的區別

src和href之間存在區別&#xff0c;能混淆使用。src用于替換當前元素&#xff0c;href用于在當前文檔和引用資源之間確立聯系。 src是source的縮寫&#xff0c;指向外部資源的位置&#xff0c;指向的內容將會嵌入到文檔中當前標簽所在位置&#xff1b;在請求src資源時會將其指向…

USACO4.12Beef McNuggets(背包+數論)

昨天晚上寫的一題 結果USACO一直掛中 今天交了下 有一點點的數論知識 背包很好想 就是不好確定上界 官方題解&#xff1a; 這是一個背包問題。一般使用動態規劃求解。 一種具體的實現是&#xff1a;用一個線性表儲存所有的節點是否可以相加得到的狀態&#xff0c;然后每次可以…

Java 循環語句中 break,continue,return有什么區別?

break 結束循環&#xff0c;跳出循環體,進行后面的程序;continue 結束本次循環&#xff0c;進行下次循環;return 跳出循環體所在的方法&#xff0c;相當于結束該方法; 例子&#xff1a; public class whiletrueTest{public static void main(String[] args) {heihei();haha();…

Epoll模型詳解

轉自http://blog.163.com/huchengsz126/blog/static/73483745201181824629285/ Linux 2.6內核中提高網絡I/O性能的新方法-epoll I/O多路復用技術在比較多的TCP網絡服務器中有使用&#xff0c;即比較多的用到select函數。 1、為什么select落后 首先&#xff0c;在Linux內核中…

運算放大器單電源應用中的使用齊納二極管偏置方法

運算放大器單電源應用中的偏置方法除了使用大電阻使運放輸出達到電源電壓的一半外&#xff0c;還有使用齊納二極管&#xff08;穩壓管&#xff09;方法也能得到達到應用目的。 下面就推薦幾個齊納二極管&#xff08;分別對應著電源電壓是15V,12V&#xff0c;9V;5V&#xff09; …

Java——demo之仿ATM操作

java.util.Scanner類&#xff0c;這是一個用于掃描輸入文本的新的實用程序。其中nextInt()獲取String型&#xff0c;而next()獲取int、double型。這是一個仿ATM的小程序。 實現條件 1.登陸界面&#xff0c;2.三次登陸機會&#xff0c;登陸成功進入登陸菜單&#xff0c;3&#x…

dpi 、 dip 、分辨率、屏幕尺寸、px、density 關系以及換算

本文轉自&#xff1a;http://www.cnblogs.com/yaozhongxiao/archive/2014/07/14/3842908.html 一、基本概念 dip &#xff1a; Density independent pixels &#xff0c;設備無關像素。 dp &#xff1a;就是dip px &#xff1a; 像素 dpi &#xf…

Ninject使用demo

public class HomeController : Controller{public ActionResult Index(){ //核心對象IKernel ninjectKernel new StandardKernel();ninjectKernel.Bind<IValueCaculator>().To<LinqValueCalcalator>(); //方案1&#xff1a;獲取接口實例IV…

Java 集合中關于Iterator 和ListIterator的詳解

1.Iterator Iterator的定義如下&#xff1a;public interface Iterator<E> {}Iterator是一個接口&#xff0c;它是集合的迭代器。集合可以通過Iterator去遍歷集合中的元素。Iterator提供的API接口如下&#xff1a;forEachRemaining(Consumer<? super E> action)&a…