在Android使用過程中,如果你想竊聽別人接收到的簡訊,達到你不可告人的目的,那麼本節內容可以實現你的需求。當系統收到簡訊時,會發出一個action名稱為android.provider.Telephony.SMS_RECEIVED的廣播Intent,該Intent存放了接收到的簡訊內容,使用名稱“pdus”即可從Intent中擷取簡訊內容。這裡面得到對象數組,數組是以位元組格式
- public class SmsBroadcastReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Object[] pduses=(Object[])intent.getExtras().get("pdus");
- for(Object pdus: pduses){
- byte[] pdusSms=(byte[])pdus;
- SmsMessage smsMessage=SmsMessage.createFromPdu(pdusSms);
- String mobile=smsMessage.getOriginatingAddress();//獲得發簡訊手機
- String content=smsMessage.getMessageBody();//獲得簡訊內容
- Date date= new Date(smsMessage.getTimestampMillis());//獲得簡訊發送時間
- SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String sendDate=simpleDateFormat.format(date);
- }
- }
- }
- 在AndroidManifest.xml檔案中的<application>節點裡對接收到簡訊的廣播Intent進行訂閱:
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter><action android:name="android.provider.Telephony.SMS_RECEIVED"/></intent-filter></receiver>
- 在AndroidManifest.xml檔案中添加以下許可權:
- <uses-permission android:name="android.permission.RECEIVE_SMS"/><!-- 接收簡訊許可權 -->
- <uses-permission android:name="android.permission.SEND_SMS"/><!-- 傳送簡訊許可權 -->
廣播接收者
除了簡訊到來廣播Intent,Android還有很多廣播Intent,如:開機啟動、電池電量變化、時間已經改變等廣播Intent。
接收電池電量變化廣播Intent ,在AndroidManifest.xml檔案中的<application>節點裡訂閱此Intent:。
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BATTERY_CHANGED"/>
- </intent-filter>
- </receiver>
- 接收開機啟動廣播Intent,在AndroidManifest.xml檔案中的<application>節點裡訂閱此Intent:
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED"/>
- </intent-filter>
- </receiver>
並且要進行許可權聲明:
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Android開發執行個體詳解之IMF
Android使用者介面設計:線性布局
Android使用者介面設計:布局基礎
GoogleAndroid UI設計技巧:新的UI設計模式