17
2014
10

Android开发学习:检测接收的短信内容(6位数字的验证码)

Android开发学习

Android开发中,通过应用程序发送短信验证码,并监听短信内容把短信验证码自动填充到文本框中,通过BroadcastReceiver检测接收的短信内容(6位数字的验证码)

新建布局文件:activity_main.xml,代码内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >


    <EditText

        android:id="@+id/et"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:gravity="center_horizontal"

        android:hint="@string/smscontent" />


</RelativeLayout>

实现的MainActivity.java代码如下:

package com.zhengdecai.detectionsmsinfo;


import java.io.UnsupportedEncodingException;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


import android.app.Activity;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.telephony.SmsMessage;

import android.text.TextUtils;

import android.util.Log;

import android.widget.EditText;


/**

 * 通过BroadcastReceiver检测接收的短信内容(6位数字的验证码)

 * 

 * @author 郑德才

 *

 */

public class MainActivity extends Activity {

private BroadcastReceiver smsReceiver;

private IntentFilter filter2;

private Handler handler;

private EditText et;

private String strContent;

private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

et = (EditText) findViewById(R.id.et);

handler = new Handler() {

public void handleMessage(Message msg) {

et.setText(strContent);

};

};

filter2 = new IntentFilter();

filter2.addAction("android.provider.Telephony.SMS_RECEIVED");

filter2.setPriority(Integer.MAX_VALUE);

smsReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

Object[] objs = (Object[]) intent.getExtras().get("pdus");

for (Object obj : objs) {

byte[] pdu = (byte[]) obj;

SmsMessage sms = SmsMessage.createFromPdu(pdu); 

String sms_mess = sms.getMessageBody();

String message = sms_mess;

try {

message = new String(sms_mess.getBytes(), "GBK");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

       

Log.d("logo", "sms     " + sms.toString()); 

Log.d("logo", "message     " + message); 

String from = sms.getOriginatingAddress();

Log.d("logo", "from     " + from); 

if (!TextUtils.isEmpty(from)) {

String code = patternCode(message);

if (!TextUtils.isEmpty(code)) {

strContent = code;

handler.sendEmptyMessage(1);

}

}

}

}

};

registerReceiver(smsReceiver, filter2);


@Override

protected void onDestroy() {

super.onDestroy();

unregisterReceiver(smsReceiver);

}

private String patternCode(String patternContent) {

if (TextUtils.isEmpty(patternContent)) {

return null;

}

Pattern p = Pattern.compile(patternCoder);

Matcher matcher = p.matcher(patternContent);

if (matcher.find()) {

return matcher.group();

}

return null;

}

}

把短信内容存储到sd卡中,然后读取短信内容实现:

package com.zhengdecai.detectionsmsinfo;


import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;


import android.annotation.SuppressLint;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.telephony.gsm.SmsMessage;

import android.util.Log;


/**

 * 把短信内容存储到sd卡中,然后读取短信内容

 * 

 * @author Administrator

 *

 */

public class SmsReceiver extends BroadcastReceiver {

private String verifyCode = "";

public static final String TAG = "SMSReceiver";

public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";


@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {

SmsMessage[] messages = getMessagesFromIntent(intent);

for (SmsMessage message : messages) {

Log.i(TAG,

message.getOriginatingAddress() + " : "

+ message.getDisplayOriginatingAddress()

+ " : " + message.getDisplayMessageBody()

+ " : " + message.getTimestampMillis());

String smsContent = message.getDisplayMessageBody();

Log.i(TAG, smsContent);

writeFile(smsContent);// 将短信内容写入SD卡

}

}

}


public final SmsMessage[] getMessagesFromIntent(Intent intent) {

Object[] messages = (Object[]) intent.getSerializableExtra("pdus");

byte[][] pduObjs = new byte[messages.length][];

for (int i = 0; i < messages.length; i++) {

pduObjs[i] = (byte[]) messages[i];

}

byte[][] pdus = new byte[pduObjs.length][];

int pduCount = pdus.length;

SmsMessage[] msgs = new SmsMessage[pduCount];

for (int i = 0; i < pduCount; i++) {

pdus[i] = pduObjs[i];

msgs[i] = SmsMessage.createFromPdu(pdus[i]);

}

return msgs;

}


// 将短信内容写到SD卡上的文件里,便于将文件pull到PC,这样可方便其它如WWW/WAP平台的自动化

@SuppressLint("SdCardPath")

public void writeFile(String str) {

String filePath = "/mnt/sdcard/verifyCode.txt";

byte[] bytes = str.getBytes();

try {

File file = new File(filePath);

file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);

fos.write(bytes);

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

创建receiver:

        <receiver android:name=".SmsReceiver" >

            <intent-filter> 

                <action android:name="android.provider.Telephony.SMS_RECEIVED" />

            </intent-filter>

        </receiver>

需要权限:

    <uses-permission android:name="android.permission.SEND_SMS" >

    </uses-permission>

    <uses-permission android:name="android.permission.RECEIVE_SMS" >

    </uses-permission>

实现运行效果图:



« 上一篇下一篇 »

评论列表:

1.药方网  2014/10/19 2:47:40 回复该留言
会安卓开发真利害。
2.光触媒  2014/10/23 13:59:01 回复该留言
真真是极好的
3.歌词大全  2014/10/27 20:02:30 回复该留言
技术文章啦支持一下。
4.maillot  2014/10/29 15:41:17 回复该留言
监听?
博主网站超赞
代码 代码
很高端的代码
8.滚筒输送机  2014/10/31 20:27:44 回复该留言
学习了。。。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。