Android中可以利用BroadcastReceiver來監聽是否收到簡訊,像是Line之類的利用簡訊來認證手輸入的手機號碼是否正確。
Android中可以利用BroadcastReceiver來監聽是否收到簡訊,像是Line之類的利用簡訊來認證手輸入的手機號碼是否正確。接收的方式很簡單,首先AndroidManifest.xml要定義權限:
然後在Application中註冊Receiver:
android:name=".SMSReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
接下來是Receiver的程式碼:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SMSReceiver extends BroadcastReceiver{
private static final String queryString = "xxxx:";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
String fromAddress = message.getOriginatingAddress();
String msg = message.getMessageBody();
if (msg.startsWith(queryString)) { //如果是接到要處理的簡訊
abortBroadcast(); //停止發送廣播給其它app
}
}
}
}
當然,一般來說不會一直開著監聽,所以我預設都是把它關掉(從AndroidManifest.xml設定android:enable為false),然後再利用啟動服務的的方式打開,收到要的之後再關掉。
final PackageManager pm = this.getPackageManager();
final ComponentName componentName = new ComponentName(this, SMSReceiver.class);
pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);