您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用Android怎么監(jiān)聽手機(jī)短信,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
前提--權(quán)限:
<uses-permission android:name="android.permission.RECEIVE_SMS" > </uses-permission> <uses-permission android:name="android.permission.READ_SMS" > </uses-permission>
定義短信廣播接收者
public class SMSBroadcastReceiverextends BroadcastReceiver{ private static OnReceivedMessageListener mOnReceivedMessageListener; public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; public SMSBroadcastReceiver(){ super(); } @Override public void onReceive(Context context, Intent intent){ if (intent.getAction().equals(SMS_RECEIVED_ACTION)) { Object[] pdus = (Object[]) intent.getExtras().get("pdus"); for(Object pdu:pdus) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu); String sender = smsMessage.getDisplayOriginatingAddress(); String content = smsMessage.getDisplayMessageBody(); long date = smsMessage.getTimestampMillis(); Date tiemDate = new Date(date); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = simpleDateFormat.format(tiemDate); //過濾不需要讀取的短信的發(fā)送號(hào)碼 if ("106902780116481".equals(sender)) { mOnReceivedMessageListener.onReceived(getDynamicPassword(content)); abortBroadcast(); } } } } public interface OnReceivedMessageListener{ void onReceived(String message); } public void setOnReceivedMessageListener(OnReceivedMessageListener onReceivedMessageListener){ this.mOnReceivedMessageListener = onReceivedMessageListener; } /** * 從字符串中截取連續(xù)6位數(shù)字組合 ([0-9]{" + 6 + "})截取六位數(shù)字 進(jìn)行前后斷言不能出現(xiàn)數(shù)字 用于從短信中獲取動(dòng)態(tài)密碼 * @param str 短信內(nèi)容 * @return 截取得到的6位動(dòng)態(tài)密碼 */ public String getDynamicPassword(String str){ // 6是驗(yàn)證碼的位數(shù),一般為六位 Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{" + 6 + "})(?![0-9])"); Matcher m = continuousNumberPattern.matcher(str); String dynamicPassword = ""; while (m.find()) { dynamicPassword = m.group(); } return dynamicPassword; } }
注冊廣播
SMSBroadcastReceiver = mSMSBroadcastReceiver = new SMSBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION); intentFilter.setPriority(Integer.MAX_VALUE); this.registerReceiver(mSMSBroadcastReceiver, intentFilter); ToastManager.getInstance().showLongToast("注冊短信監(jiān)聽"); mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.OnReceivedMessageListener() { @Override public void onReceived(String message){ //do something } });
方式二:監(jiān)聽短信數(shù)據(jù)庫
內(nèi)容提供者中對外通信方式有3種:
方式1:定義為Activity的內(nèi)部類,直接在onChang()方法中處理業(yè)務(wù)邏輯,比如收到短信之后設(shè)置給EditText
優(yōu)點(diǎn):方便
缺點(diǎn):耦合度高,復(fù)用性差
方式2:定義接口,Activity實(shí)現(xiàn)這個(gè)接口,拿到回調(diào),處理業(yè)務(wù)邏輯
優(yōu)點(diǎn):耦合度低,復(fù)用性高
缺點(diǎn)沒用充分利用Handler資源
代碼如下:
/** * Created by wxw on 2016/9/24 10:34 * function: 監(jiān)聽短信數(shù)據(jù)庫 * e-mail:wangxw725@163.com */ public class SmsContentObserverextends ContentObserver{ private Cursor cursor = null; private Context mContext; private String[] projection = new String[]{"_id","body"}; private OnMessageObservedListener mOnMessageObservedListener; public SmsContentObserver(Context context,Handler handler){ super(handler); this.mContext = context; } public interface OnMessageObservedListener{ void onObservedMessage(String message); } public void setOnMessageObservedListener(OnMessageObservedListener onMessageObservedListener){ this.mOnMessageObservedListener = onMessageObservedListener; } @Override public void onChange(boolean selfChange){ super.onChange(selfChange); cursor = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), projection,null, null, "_id desc"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToNext(); int smsbodyColumn = cursor.getColumnIndex("body"); String smsBody = cursor.getString(smsbodyColumn); mOnMessageObservedListener.onObservedMessage(getDynamicPassword(smsBody)); } cursor.close(); } private String getDynamicPassword(String str){ Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{" + 6 + "})(?![0-9])"); Matcher m = continuousNumberPattern.matcher(str); String dynamicPassword = ""; while (m.find()) { dynamicPassword = m.group(); } return dynamicPassword; } }
方式3:通過Handler發(fā)送消息,在Activity中進(jìn)行業(yè)務(wù)邏輯處理
代碼如下:
/** * Created by wxw on 2016/9/24 10:34 * function: 監(jiān)聽短信數(shù)據(jù)庫 * e-mail:wangxw725@163.com */ public class SmsContentObserverextends ContentObserver{ private Cursor cursor = null; private Context mContext; private Handler mHandler; private String[] projection = new String[]{"_id","body"}; public SmsContentObserver(Context context,Handler handler){ super(handler); this.mContext = context; this.mHandler = handler; } @Override public void onChange(boolean selfChange){ super.onChange(selfChange); cursor = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), projection,null, null, "_id desc"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToNext(); int smsbodyColumn = cursor.getColumnIndex("body"); String smsBody = cursor.getString(smsbodyColumn); mHandler.obtainMessage(1,getDynamicPassword(smsBody)).sendToTarget(); } cursor.close(); } private String getDynamicPassword(String str){ Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{" + 6 + "})(?![0-9])"); Matcher m = continuousNumberPattern.matcher(str); String dynamicPassword = ""; while (m.find()) { dynamicPassword = m.group(); } return dynamicPassword; } }
注冊觀察者
smsContentObserver = new SmsContentObserver(this, smsHandler); getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContentObserver);
handler中處理消息
private Handler smsHandler = new Handler(){ @Override public void handleMessage(Message msg){ switch (msg.what){ case 0: ...... break; case 1: LogUtils.x("Activity收到了短息碼:"+(String)msg.obj); lf.mEtPassword.setText((String)msg.obj); break; } } };
注銷觀察者
@Override protected void onDestroy(){ super.onDestroy(); ...... if(smsContentObserver!=null){ getContentResolver().unregisterContentObserver(smsContentObserver); smsContentObserver = null; } }
關(guān)于使用Android怎么監(jiān)聽手機(jī)短信就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。