Android 数据库 短信 监听

Android 实现监听短信(同一时候监听广播和数据库)代码例如以下:

  1. 拦截广播

    package com.javen.sms.receiver;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    
    import com.javen.util.InterceptKeyKeeper;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.telephony.SmsMessage;
    import android.util.Log;
    import android.widget.Toast;
    
    public class SmsReceiver extends BroadcastReceiver {
        private Context mContext;
        public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
        public static final String SMS_DELIVER_ACTION = "android.provider.Telephony.SMS_DELIVER";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            this.mContext=context;
            Toast.makeText(context, "接收短信运行了.....", Toast.LENGTH_LONG).show();
            Log.e("SMSReceiver, isOrderedBroadcast()=", isOrderedBroadcast()+"");
            Log.e("SmsReceiver onReceive...", "接收短信运行了......");
            String action = intent.getAction();
            if (SMS_RECEIVED_ACTION.equals(action) || SMS_DELIVER_ACTION.equals(action)) {
                Toast.makeText(context, "開始接收短信.....", Toast.LENGTH_LONG).show();
                Log.e("SmsReceiver onReceive...", "開始接收短信.....");
    
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[])bundle.get("pdus");
                    if (pdus != null && pdus.length > 0) {
                        SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            byte[] pdu = (byte[]) pdus[i];
                            messages[i] = SmsMessage.createFromPdu(pdu);
                        }
                        for (SmsMessage message : messages) {
                            String content = message.getMessageBody();// 得到短信内容
                            String sender = message.getOriginatingAddress();// 得到发信息的号码
                            if (content.contains(InterceptKeyKeeper.getInterceptKey(mContext))) {
                                Toast.makeText(mContext, "内容为:"+content, Toast.LENGTH_LONG).show();
                                //setResultData(null);
                                this.abortBroadcast();// 中止
                            }else if (sender.equals("10010") || sender.equals("10086")) {
                                Toast.makeText(mContext, "内容为:"+content, Toast.LENGTH_LONG).show();
                                this.abortBroadcast();// 中止
                            }
                            Date date = new Date(message.getTimestampMillis());
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
                            String sendContent = format.format(date) + ":" + sender + "--" + content;
                            Log.e("SmsReceicer onReceive ",sendContent +" ");
                        }
                    }
                }
            }
        }
    }

  2. 开启一个服务开监听数据库

    package com.javen.service;
    
    import android.app.Service;
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.IBinder;
    import android.os.Process;
    import android.widget.Toast;
    
    /**
     * @author Javen
     * 开启一个服务开监听数据库
     */
    public class SmsService extends Service {
    
        private SmsObserver mObserver;
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            Toast.makeText(this, "SmsService 服务器启动了....", Toast.LENGTH_LONG).show();
            // 在这里启动
            ContentResolver resolver = getContentResolver();
            mObserver = new SmsObserver(resolver, new SmsHandler(this));
            resolver.registerContentObserver(Uri.parse("content://sms"), true,mObserver);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            this.getContentResolver().unregisterContentObserver(mObserver);
            Process.killProcess(Process.myPid());
        }
    }

  3. 数据库观察者

    package com.javen.service;
    
    import android.content.ContentResolver;
    import android.database.ContentObserver;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Message;
    import android.util.Log;
    
    /**
     * @author Javen
     * 数据库观察者
     */
    public class SmsObserver extends ContentObserver {
    
        private ContentResolver mResolver;
        public SmsHandler smsHandler;
    
        public SmsObserver(ContentResolver mResolver, SmsHandler handler) {
            super(handler);
            this.mResolver = mResolver;
            this.smsHandler = handler;
        }
    
        @Override
        public void onChange(boolean selfChange) {
            Log.i("SmsObserver onChange ", "SmsObserver 短信有改变");
            Cursor mCursor = mResolver.query(Uri.parse("content://sms/inbox"),
                    new String[] { "_id", "address", "read", "body", "thread_id" },
                    "read=?
    
    ", new String[] { "0" }, "date desc");
    
            if (mCursor == null) {
                return;
            } else {
                while (mCursor.moveToNext()) {
                    SmsInfo _smsInfo = new SmsInfo();
    
                    int _inIndex = mCursor.getColumnIndex("_id");
                    if (_inIndex != -1) {
                        _smsInfo._id = mCursor.getString(_inIndex);
                    }
    
                    int thread_idIndex = mCursor.getColumnIndex("thread_id");
                    if (thread_idIndex != -1) {
                        _smsInfo.thread_id = mCursor.getString(thread_idIndex);
                    }
    
                    int addressIndex = mCursor.getColumnIndex("address");
                    if (addressIndex != -1) {
                        _smsInfo.smsAddress = mCursor.getString(addressIndex);
                    }
    
                    int bodyIndex = mCursor.getColumnIndex("body");
                    if (bodyIndex != -1) {
                        _smsInfo.smsBody = mCursor.getString(bodyIndex);
                    }
    
                    int readIndex = mCursor.getColumnIndex("read");
                    if (readIndex != -1) {
                        _smsInfo.read = mCursor.getString(readIndex);
                    }
    
                    // 依据你的拦截策略。推断是否不正确短信进行操作;将短信设置为已读;将短信删除
                    // TODO
                    System.out.println("获取的短信内容为:"+_smsInfo.toString());
                    Log.i("SmsObserver ...", "获取的短信内容为:"+_smsInfo.toString());
                    Message msg = smsHandler.obtainMessage();
                    _smsInfo.action = 2;// 0不正确短信进行操作;1将短信设置为已读;2将短信删除
                    msg.obj = _smsInfo;
                    smsHandler.sendMessage(msg);
                }
            }
    
            if (mCursor != null) {
                mCursor.close();
                mCursor = null;
            }
        }
    }

  4. 短信处理类

    package com.javen.service;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.net.Uri;
    import android.os.Handler;
    import android.os.Message;
    
    /**
     * @author Javen
     *
     *         短信的处理
     *
     */
    public class SmsHandler extends Handler {
        private Context mcontext;
    
        public SmsHandler(Context context) {
            this.mcontext = context;
        }
    
        @Override
        public void handleMessage(Message msg) {
            SmsInfo smsInfo = (SmsInfo) msg.obj;
    
            if (smsInfo.action == 1) {
                ContentValues values = new ContentValues();
                values.put("read", "1");
                mcontext.getContentResolver().update(
                        Uri.parse("content://sms/inbox"), values, "thread_id=?",
                        new String[] { smsInfo.thread_id });
            } else if (smsInfo.action == 2) {
                Uri mUri = Uri.parse("content://sms/");
                mcontext.getContentResolver().delete(mUri, "_id=?",
                        new String[] { smsInfo._id });
            }
        }
    }

  5. SmsInfo
    数据结构 主要用于短信拦截

    package com.javen.service;
    
    /**
     * 主要用于短信拦截
     *
     * @author Javen
     *
     */
    public class SmsInfo {
        public String _id = "";
        public String thread_id = "";
        public String smsAddress = "";
        public String smsBody = "";
        public String read = "";
        public int action = 0;// 1代表设置为已读,2表示删除短信
        @Override
        public String toString() {
            return "SmsInfo [_id=" + _id + ", thread_id=" + thread_id
                    + ", smsAddress=" + smsAddress + ", smsBody=" + smsBody
                    + ", read=" + read + ", action=" + action + "]";
        }
    
    }

  6. 须要的权限以及配置信息

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.javen.sms"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />
    
        <uses-permission android:name="android.permission.SEND_SMS" />
         <uses-permission android:name="android.permission.RECEIVE_SMS" />
    
         <!-- <uses-permission android:name="android.permission.BROADCAST_SMS" />
         <uses-permission android:name="android.permission.READ_SMS" />
        <uses-permission android:name="android.permission.WRITE_SMS" /> -->
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
             <receiver
                android:name="com.javen.sms.receiver.SmsReceiver"
                android:exported="true"
                android:permission="android.permission.BROADCAST_SMS">
                <intent-filter android:priority="2147483647" >
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                    <action android:name="android.provider.Telephony.SMS_DELIVER" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </receiver>
    
            <service android:name="com.javen.service.SmsService"></service>
        </application>
    
    </manifest>

  7. 測试在MainActivity 中启动SmsService
     发送短信到10086 或者10010就可以測试

            intentService = new Intent(this, SmsService.class);
            startService(intentService);
            Toast.makeText(this, "启动service中.....", 1).show();
    

转载自:http://www.cnblogs.com/zyw-205520/p/4764177.html

时间: 2024-10-29 10:48:09

Android 数据库 短信 监听的相关文章

Android实战简易教程-第四十枪(窃听风云之短信监听)

近期在做监听验证码短信自己主动填入的功能,无意间想到了一个短信监听的办法. 免责声明:短信监听本身是一种违法行为,这里仅仅是技术描写叙述.请大家学习技术就可以.(哈哈) 本实例是基于bmob提供的后台服务,将监听到的短信自己主动上传到bmob数据库中. 一.代码实现: 1.首先实现javabean对象. package com.example.messagecut; import cn.bmob.v3.BmobObject; public class MsgContent extends Bmo

Android短信监听(三)——利用Loader实现短信监听

MainActivity如下: package cc.c; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.app.LoaderManager.LoaderCallbacks; import android.content.Context; import android.content.Loader; import android.database.Curs

Android短信监听(二)——利用ContentObserver实现短信监听

MainActivity如下: package cc.testsmslistener; import cc.testsmslistener.SMSContentObserver.MessageListener; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; import android.app.Activity; /** *

Android短信监听(一)——利用BroadcastReceiver实现短信监听

MainActivity如下: package cc.testsmsbroadcastreceiver; import cc.testsmsbroadcastreceiver.SMSBroadcastReceiver.MessageListener; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; /** * Demo描述: * 利用BroadcastReceiver实现

wemall app商城源码Android短信监听接收器

wemall doraemon是Android客户端程序,服务端采用wemall微信商城,不对原商城做任何修改,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可随意定制修改.本文分享其中短信监听接收器,用于自动获取短信验证码,然后自动填写到验证码区域代码,供技术员参考学习. package cn.smssdk.gui; import android.content.BroadcastReceiver; import android.content.Context; import a

Android 编程下短信监听在小米手机中失效的解决办法

相信很多人写的短信监听应用在小米手机上是拦截不到短信的,这是因为小米对短信的处置权优先分给了系统.我们可以在短信的[设置]→[高级设置]→[系统短信优先]中发现短信的优先处理权默认是分给系统的,只要关闭这个系统优先权,短信监听应用就可以正常的拦截到短信了.   

内容观察者实现短信监听

内容观察者实现短信监听 通过内容观察者监听短信是否发生变化,如果发生变化,就用内容提供者读取短信的内容. 原理: 当短信发生变化(比如说来短信),短信应用就会通知内容观察者我的短信发生了变化,并把变化位置短信的uri传过来,有uri之后,内容提供者就可以很方便的读取短信内容了,不过肯定要保证权限够. package com.example.duanxinjianting; import android.app.Activity; import android.database.ContentOb

短信监听+短信拦截

监听消息发送和消息是否被接收. import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.provider.Telephony.Sms; import android.telephony.SmsManager; i

android获取短信验证码并自动填写的实现一

android获取短信验证码并自动填写的实现一 android获取短信验证码并自动填写的实现一,有需要的朋友可以参考下. 现在的应用在注册登录或者修改密码中都用到了短信验证码,那在android中是如何实现获取短信验证码并自动填写的呢? 首先,需要要在manifest中注册接收和读取短信的权限: <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> &l