編輯:關於 Android 程式設計
每一部手機都具備短信收發能力,在 Android 上分別靠「攔截系統廣播」與「SmsManager」來完成。以下分兩部分實作。
整體步驟:
布局用來顯示發送者號碼與內容:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/sms_from"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="From" />
<TextView android:id="@+id/sms_from_txt"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@id/sms_from"/>
<TextView android:id="@+id/sms_content"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="@id/sms_from"
android:layout_marginTop="20dp"
android:text="Content" />
<TextView android:id="@+id/sms_content_txt"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:layout_below="@id/sms_from_txt"
android:layout_toRightOf="@id/sms_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private TextView fromTv;
private TextView contentTv;
private IntentFilter intentFilter;
private MessageReceiver messageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
getSms();
}
private void getSms() {
intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver = new MessageReceiver();
// 設置較高的優先級
intentFilter.setPriority(100);
registerReceiver(messageReceiver, intentFilter);
}
private void initView() {
fromTv = (TextView) findViewById(R.id.sms_from_txt);
contentTv = (TextView) findViewById(R.id.sms_content_txt);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
}
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
// 提取短信消息
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
// 獲取發送方號碼
String address = messages[0].getOriginatingAddress();
String fullMessage = "";
for (SmsMessage message : messages) {
// 拼接短信內容
fullMessage += message.getMessageBody();
}
// 截斷廣播
abortBroadcast();
fromTv.setText(address);
contentTv.setText(fullMessage);
}
}
}
兩個重點:註冊的廣播接收器必須在 onDestroy() 中取消註冊,否則會造成記憶體洩漏與重複接收。
另外,短信廣播是有序廣播,因此接收器的優先級與 abortBroadcast() 的組合決定了「誰先看到這則短信」。要不要截斷,取決於你的應用是否要取代系統簡訊程式的角色——這是一個會直接影響使用者體驗的決定,不建議在一般應用中隨意截斷。
步驟:
onDestroy() 中取消註冊 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="@+id/to_ed"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="to"/>
<EditText android:id="@+id/to_content"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="@id/to_ed"
android:hint="content"/>
<Button android:id="@+id/send_msg"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="@id/to_content"
android:text="@string/send_message"/>
</RelativeLayout>
public class SendMsgActivity extends AppCompatActivity implements View.OnClickListener {
private Context context;
private EditText toEdit;
private EditText toContent;
private IntentFilter sendFilter;
private SendStatusReceiver sendStatusReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_msg);
context = this;
initView();
}
private void initView() {
toEdit = (EditText) findViewById(R.id.to_ed);
toContent = (EditText) findViewById(R.id.to_content);
Button sendMsg = (Button) findViewById(R.id.send_msg);
sendMsg.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_msg:
sendMessage();
break;
default:
break;
}
}
private void sendMessage() {
String to = toEdit.getText().toString();
String content = toContent.getText().toString();
// 獲得廣播接收器實例和 IntentFilter 實例
sendStatusReceiver = new SendStatusReceiver();
sendFilter = new IntentFilter();
sendFilter.addAction("SENT_SMS_ACTION");
registerReceiver(sendStatusReceiver, sendFilter);
// 構造 PendingIntent 啟動短信發送狀態監控廣播
Intent sendIntent = new Intent("SENT_SMS_ACTION");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, sendIntent, 0);
// 獲得短信管理實例並發送
// 參數依次為:接收者號碼、serviceCenterAddress、短信內容、發送結果 PendingIntent、送達結果 PendingIntent
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(to, null, content, pi, null);
}
/** 監控短信是否發送成功 */
class SendStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (getResultCode() == RESULT_OK) {
Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(sendStatusReceiver);
}
}
權限宣告:
<uses-permission android:name="android.permission.SEND_SMS"/>
權限與上架政策。SEND_SMS 與 RECEIVE_SMS 都屬於高風險權限。若你的應用不是「預設短信處理程式」,在 Google Play 上申請這類權限會被要求提交嚴格說明,多數情況會被駁回。請先確認產品定位是否真的需要,否則應改用系統的 ACTION_SENDTO 把編輯工作交給簡訊 App。
長短信要分段。sendTextMessage() 單次有長度上限,超出時應先用 smsManager.divideMessage(content) 切段後逐段發送,並自行處理收端的拼接順序。
發送結果要抽屜化判斷。getResultCode() 回傳 RESULT_OK 只代表「已交給電信網路」,不代表對方收到。送達確認要另外監聽 sendTextMessage() 的第五個參數(deliveredIntent)。
Android 6.0 以上要動態申請。僅在 manifest 宣告已不足夠,執行期必須透過 requestPermissions() 取得使用者同意,並處理被拒絕的情況。
鈕扣電池常見規格型號一覽
鈕扣電池的型號通常印製在電池背面,由字母與阿拉伯數字組成。了解一些基本的型號知識對日常生活頗有幫助,因為我們常見的兒童玩具、電路主板、電子錶、遙控器等裝置都會用到,一旦需
如何預置 Android 手機 APK:四種情境完整教學
預置 APK 依需求可分為以下四種情境: 1. 如何將「帶源碼」的 APK 預置進系統? 2. 如何將「無源碼」的 APK 預置進系統? 3. 如何預置 APK 使得使用
Android 4.4 之後 WebView 開發必看的七大注意事項
從 Android 4.4 開始,系統內建的 WebView 改以 Chromium 為核心(這大概和 Android 部門負責人由 Andy Rubin 換成 Chro
Android Studio 中文變成豆腐方塊?改一個字型設定就解決
剛裝好 Android Studio,打開一看:介面上的中文、LogCat 裡的中文輸出,全都變成一個個空心的小方框。程式碼沒問題、編碼也沒問題,問題出在 IDE 找不到