Android
- 首先我們要寫一個廣播接收器垃僚,當(dāng)我們的手機收到短信時意敛,系統(tǒng)會自動發(fā)送一個廣播吗货,我們只需要接收到這條廣播就可以了
- 在廣播里面急前,我們重寫的onReceive()方法,通過里面的Intent寫到的Bundle就可以拿到短信的內(nèi)容
- 清單文件里面我們必須要添加權(quán)限宅广,否則無法接收到葫掉。
- 為了防止我們的廣播接收不到,我們自己寫的廣播接收器的權(quán)限必須要大跟狱,以防萬一俭厚,我設(shè)置了1000。
步驟詳解:
- 定義一個廣播接收器SmsReceiver驶臊,并繼承
BroadcastReceiver
挪挤,同時重寫onReceive()方法:
package com.nlte.phonesafe.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.SmsMessage;
import com.nlte.phonesafe.R;
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//判斷廣播消息
if (action.equals(SMS_RECEIVED_ACTION)){
Bundle bundle = intent.getExtras();
//如果不為空
if (bundle!=null){
//將pdus里面的內(nèi)容轉(zhuǎn)化成Object[]數(shù)組
Object pdusData[] = (Object[]) bundle.get("pdus");// pdus :protocol data unit :
//解析短信
SmsMessage[] msg = new SmsMessage[pdusData.length];
for (int i = 0;i < msg.length;i++){
byte pdus[] = (byte[]) pdusData[i];
msg[i] = SmsMessage.createFromPdu(pdus);
}
StringBuffer content = new StringBuffer();//獲取短信內(nèi)容
StringBuffer phoneNumber = new StringBuffer();//獲取地址
//分析短信具體參數(shù)
for (SmsMessage temp : msg){
content.append(temp.getMessageBody());
phoneNumber.append(temp.getOriginatingAddress());
}
System.out.println("發(fā)送者號碼:"+phoneNumber.toString()+" 短信內(nèi)容:"+content.toString());
//可用于發(fā)命令執(zhí)行相應(yīng)的操作
/* if ("#*location*#".equals(content.toString().trim())){
abortBroadcast();//截斷短信廣播
}else if ("#*alarm*#".equals(content.toString().trim())){
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.guoge);
//播放音樂
mediaPlayer.start();
abortBroadcast();//截斷短信廣播
}else if ("#*wipe*#".equals(content.toString().trim())){
abortBroadcast();//截斷短信廣播
}else if ("#*lockscreen*#".equals(content.toString().trim())){
abortBroadcast();//截斷短信廣播
}*/
}
}
}
}
- 在AndroidManifest.xml注冊廣播接收器,并添加相應(yīng)的權(quán)限:
2.1 注冊廣播接收器
<receiver android:name=".receiver.SmsReceiver">
<intent-filter android:priority="1000"> <!--優(yōu)先級:-1000~1000关翎,系統(tǒng)短信優(yōu)先級為-1-->
<!--訂閱廣播事件類型-->
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
2.2 添加權(quán)限
<!--收短信的權(quán)限-->
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<!--讀取短信信息的權(quán)限-->
<uses-permission android:name="android.permission.READ_SMS"/>