編輯:關於 Android 程式設計
廣播(BroadcastReceiver)是 Android 元件之間鬆耦合溝通的重要機制,基於「發布/訂閱」模型實作,發送方不必知道誰在聽,接收方也不必知道訊息從哪來。
廣播發出之後,只有訂閱了該訊息的接收者才會收到並處理。整個流程可以拆成三步:
onReceive()。關鍵特性是非同步:發送者投出廣播後不會等待,也不關心是否有人接收、對方何時才收到。這讓廣播非常適合處理「狀態變更通知」這類不需要回覆的事件。
靜態註冊(寫在 Manifest 的 receiver 標籤)——應用未啟動時也能收到廣播,但從 Android 8.0 起,多數隱含式廣播已不再允許這種方式。
動態註冊(呼叫 registerReceiver())——只在元件存活期間有效,必須在適當時機呼叫 unregisterReceiver() 解除,否則會造成記憶體洩漏。常見做法是在 onResume 註冊、onPause 解除。
以下範例示範如何以廣播接收簡訊的「發送中」與「已送達」狀態。
BroadcastReceiverHelper.java —— 接收廣播並提示
package com.scd.broadcastreceiver.helper;
import com.scd.broadcastreceiver.activity.MainActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BroadcastReceiverHelper extends BroadcastReceiver {
private MainActivity mActivity = null;
public BroadcastReceiverHelper(MainActivity mContext) {
super();
mActivity = mContext;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MainActivity.ACTION_SENDMESSAGE)) {
toast("發送成功");
} else if (intent.getAction().equals(MainActivity.ACTION_DELIVERMESSAGE)) {
toast("接收成功");
}
}
public void toast(String text) {
Toast.makeText(mActivity, text, Toast.LENGTH_SHORT).show();
}
}
MainActivity.java —— 註冊廣播並發送簡訊
public class MainActivity extends Activity implements OnClickListener {
private Button mButton = null;
/** 簡訊已送出 */
public static String ACTION_SENDMESSAGE = "com.scd.broadcastreceiver.MainActivity.SendMessage";
/** 簡訊已送達 */
public static String ACTION_DELIVERMESSAGE = "com.scd.broadcastreceiver.MainActivity.DeliverMessage";
private BroadcastReceiverHelper mHelperS = null;
private BroadcastReceiverHelper mHelperD = null;
private SmsManager mSmsManager = null;
private String mTelephone = "13607567010";
private String mContext = "你好,有什麼需要幫助的嗎?";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.sendBroadcast);
mButton.setOnClickListener(this);
mSmsManager = SmsManager.getDefault();
registerBroadcast();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendBroadcast:
sendBroadcastReceiver(mTelephone, mContext);
break;
}
}
/** 註冊兩個廣播:送出成功、送達成功 */
public void registerBroadcast() {
mHelperS = new BroadcastReceiverHelper(MainActivity.this);
this.registerReceiver(mHelperS, new IntentFilter(ACTION_SENDMESSAGE));
mHelperD = new BroadcastReceiverHelper(MainActivity.this);
this.registerReceiver(mHelperD, new IntentFilter(ACTION_DELIVERMESSAGE));
}
/**
* 發送簡訊。
* 送出時會觸發一次廣播,對方收到時也會觸發一次。
*/
public void sendBroadcastReceiver(String telephone, String content) {
if (telephone != null) {
Intent sIntent = new Intent(ACTION_SENDMESSAGE);
// 簡訊成功送出後才發送
PendingIntent sentIntent = PendingIntent.getBroadcast(MainActivity.this, 0, sIntent, 0);
Intent dIntent = new Intent(ACTION_DELIVERMESSAGE);
// 對方收到簡訊後才發送
PendingIntent deliveryIntent = PendingIntent.getBroadcast(MainActivity.this, 0, dIntent, 0);
mSmsManager.sendTextMessage(telephone, null, content, sentIntent, deliveryIntent);
}
}
}
必要的權限宣告
<!-- 簡訊權限 --> <uses-permission android:name="android.permission.SEND_SMS" > </uses-permission> <uses-permission android:name="android.permission.READ_SMS" > </uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS" > </uses-permission>
動態註冊要記得解除。範例中在 onCreate 註冊,但沒有在 onDestroy 解除,正式專案請務必補上,否則 Activity 被回收後接收者仍在,容易造成記憶體洩漏或空指標。
別在 onReceive 裡做長時間工作。onReceive() 執行在主執行緒,且有約 10 秒的執行上限,逾時會被系統判定為 ANR。需要耗時處理時,請在 onReceive 中轉交給 Service 或 goAsync() 處理。
簡訊權限屬高風險項目。SEND_SMS 屬於需執行期請求的危險權限,且 Google Play 對使用這組權限的應用有嚴格審查,非預設簡訊應用很難通過。若只是需要 App 內部的元件溝通,用自訂 action 的廣播或 LiveData 即可,不必動用簡訊權限。
此外,Android 4.4 之後撰寫簡訊需改用 SmsManager 的多元件方法(如 divideMessage() 搭配 sendMultipartTextMessage())以正確處理長簡訊,直接送長字串可能只送出前半段。
用RenderScript快速打造Android高斯模糊效果
前言 近年來,模糊效果已經成為眾多App界面設計中的常客,而這背後靠的正是高斯模糊。眾所周知,在Android平台上進行模糊渲染是一件相當吃CPU又頗耗時的任務,稍有不慎
仿微信相册:手把手实现图片选择器
仿微信图片选择器 源码下载链接:见文末。 先上图,后上代码: 打开 app 后点击「添加图片」按钮: 获取所选图片,并在 gridview 中返回显示: 实现该功
Android NDK r9 環境配置與第一個 JNI 程序
NDK 是一套工具集,讓你能夠在應用中通過 C、C++ 等原生代碼語言實現部分功能。Android NDK 是在 SDK 前面加上了「原生」二字,即 Native Dev
Android Studio 安裝常見錯誤:HAXM 與 VT-x 排查
Android Studio 1.0 推出後,越來越多開發者從 Eclipse 遷移。安裝完成後,新建專案看似順利,但啟動模擬器時卻可能遇到硬體加速相關錯誤。 模擬器啟