Android利用BroadcastReceiver接收本地廣播與跨專案(APP)接收廣播
阿新 • • 發佈:2019-02-17
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreceiverdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.t20.broadcastreceiverdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 自己接收自己的廣播,註冊靜態的廣播接收器,MainActivity$MyReceiver表示呼叫MainActivity裡面的公共靜態類MyReceiver --> <!-- $符號,表示呼叫內部類 --> <receiver android:name="com.t20.broadcastreceiverdemo.MainActivity$MyReceiver"> <!-- 廣播優先順序 範圍0-1000 預設值是500 --> <intent-filter android:priority="1000"> <!-- 接收廣播,和廣播發送器的意圖一致 --> <action android:name="com.t20.broadcast" /> </intent-filter> </receiver> </application> </manifest>
二、跨專案接收廣播(另外一個專案或APP作為接收器)
1.MyReceiver.java檔案中(接收器)
package com.t20.Receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //對下傳廣播資訊進行修改 setResultData("每人工資只漲20元"); /*//接收標準廣播(無序廣播)資訊 String data=intent.getStringExtra("data");*/ //接收有序廣播資訊 String ret=getResultData(); Log.i("接收到來自其他專案的廣播", "廣播內容:"+ret); //終止廣播下傳,後續(下一級)的接收器不會再接受到廣播 abortBroadcast(); } }
2.AndroidManifest.xml檔案中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreceiver1" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.t20.broadcastreceiver.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 註冊靜態的廣播接收器 --> <receiver android:name="com.t20.Receiver.MyReceiver"> <!-- priority廣播優先順序 範圍0-1000, 預設值是500,1000最高 --> <intent-filter android:priority="800"> <!-- 廣播名,和廣播發送器(廣播站)的意圖一致 --> <action android:name="com.t20.broadcast" /> </intent-filter> </receiver> </application> </manifest>