Android 短信拦截+来去电话拦截
jopen
9年前
一.短信拦截分为2种方式,其一是广播,其二是内容观察者
如何判断android 短信发送(sendTextMessage)是否成功
第一种是通过BroadcastReciver
<uses-permission android:name="android.permission.RECEIVE_SMS"/> <!-- 拦截短信(就是接受短些的权限) --> <receiver android:name="com.demo.artshell.broadcastreceiverdemo.InterceptReceiver"> <!-- 这里没有设置android:enable和android:exported属性,<a href="http://developer.android.com/guide/topics/manifest/receiver-element.html" target="_blank" rel="nofollow">参考官方文档</a> --> <!--这里的优先级为1000,假定你手机中没有安装其他第三方短信拦截软件,如360等,否则其他第三方软件拦截权限过高导致你都应用程序拦截不到短信--> <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver
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; import java.text.SimpleDateFormat; import java.util.Date; public class InterceptReceiver extends BroadcastReceiver { public static final String TAG = "InterceptReceiver"; public static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; public InterceptReceiver() {} @Override public void onReceive(Context context, Intent intent) { Log.i(TAG,"---------------InterceptReceiver onReceive()----------------"); if (ACTION_SMS_RECEIVED.equals(intent.getAction())) { Bundle carryContent = intent.getExtras(); if (carryContent != null) { StringBuilder sb = new StringBuilder(); // 通过pdus获取接收到的所有短信息,获取短信内容 Object[] pdus = (Object[]) carryContent.get("pdus"); // 构建短信对象数组 SmsMessage[] mges = new SmsMessage[pdus.length]; for (int i = 0, len = pdus.length; i < len; i++) { // 获取单条短信内容,以pdu格式存,并生成短信对象 mges[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } for (SmsMessage mge : mges) { sb.append("短信来自:" ).append(mge.getDisplayOriginatingAddress()).append("\n") .append("短信内容:").append(mge.getMessageBody()).append("\n"); Date sendDate = new Date(mge.getTimestampMillis()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sb.append("短信发送时间:").append(format.format(sendDate)); } Log.i(TAG,sb.toString()); // 打印日志记录 Toast.makeText(context,sb.toString(),Toast.LENGTH_LONG).show(); this.abortBroadcast(); // 不再往下传播 } } } }
第二种通过ContentObserver
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿
content://sms/outbox 发件箱
content://sms/failed 发送失败
content://sms/queued 待发送列表
private SmsObserver smsObserver; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.app_login); smsObserver = new SmsObserver(this, null); getContentResolver().registerContentObserver(SMS_INBOX, true, smsObserver); } protected void onstop() { super.onstop(); //必须解除注册,否则Activity不能销毁 getContentResolver().unregisterContentObserver(smsObserver); } class SmsObserver extends ContentObserver { public SmsObserver(Context context, Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); //每当有新短信到来时,使用我们获取短消息的方法 getSmsFromPhone(); } }
查询数据库
private Uri SMS_INBOX = Uri.parse("content://sms/inbox"); public void getSmsFromPhone() { ContentResolver cr = getContentResolver(); String[] projection = new String[] { "body" };//"_id", "address", "person",, "date", "type String where = " address = '1066321332' AND date > " + (System.currentTimeMillis() - 10 * 60 * 1000); Cursor cur = cr.query(SMS_INBOX, projection, where, null, "date desc"); if (null == cur) return; if (cur.moveToNext()) { String number = cur.getString(cur.getColumnIndex("address"));//手机号 String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表 String body = cur.getString(cur.getColumnIndex("body")); //这里我是要获取自己短信服务号码中的验证码~~ Pattern pattern = Pattern.compile(" [a-zA-Z0-9]{10}"); Matcher matcher = pattern.matcher(body); if (matcher.find()) { String res = matcher.group().substring(1, 11); mobileText.setText(res); } } }
sms主要结构:
_id:短信序号,如100 thread_id:对话的序号,如100,与同一个手机号互发的短信,其序号是相同的 address:发件人地址,即手机号,如+86138138000 person:发件人,如果发件人在通讯录中则为具体姓名,陌生人为null date:日期,long型,如1346988516,可以对日期显示格式进行设置 protocol:协议0SMS_RPOTO短信,1MMS_PROTO彩信 read:是否阅读0未读,1已读 status:短信状态-1接收,0complete,64pending,128failed type:短信类型1是接收到的,2是已发出 body:短信具体内容 service_center:短信服务中心号码编号,如+8613800755500
Android4.4方案有些问题,看这里
------------------------------------------------
推荐博客:
二.电话来去电拦截
public class CallPhoneActivity extends Activity { private CallPhoneBroadcastReceiver mBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_phone); mBroadcastReceiver = new CallPhoneBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);//添加此Action来拦截来去电电话 intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);//添加此Action来拦截来电电话状态 registerReceiver(mBroadcastReceiver, intentFilter); } @Override protected void onDestroy() { //取消注册,防止内存溢出 unregisterReceiver(mBroadcastReceiver); super.onDestroy(); } public class CallPhoneBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { AudioManager mAudioManager=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE); String inComingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);//去电 String outGogingNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); //来电 String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE); if(Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) { if (outGogingNumber == null) { outGogingNumber = getResultData(); } if (shouldCancel(outGogingNumber)) //判断号码是不是需要拦截 { mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); setResultData(null); mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); } else { setResultData(reformatNumber(outGogingNumber)); } Log.i("TAG", "去电号码:phoneState="+phoneState+",phoneNumber="+outGogingNumber); } else if(!TextUtils.isEmpty(inComingNumber) && TelephonyManager.EXTRA_STATE_RINGING.equals(phoneState)) { //关于来电拦截,网上例子很多,如:http://blog.csdn.net/wangfayinn/article/details/8004023 //注意TelephonyManager.EXTRA_STATE_RINGING.equals(phoneState)必须判断,否则来去电判断不准确 Log.e("TAG", "来电号码:inComingNumber="+phoneState+",phoneNumber="+inComingNumber); } } //拦截变更号码 private String reformatNumber(String phoneNumber) { return "17951".concat(phoneNumber); } //判断该号码是否为危险号码 private boolean shouldCancel(String phoneNumber) { return "13002248003".equals(phoneNumber); } } /** * 摸你去电 * @param v */ public void onClickToCallPhone(View v) { Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:13724551306")); startActivity(intent); } }
注意TelephonyManager.EXTRA_STATE_RINGING.equals(phoneState)必须判断,否则来去电判断不准确
权限
<!-- 呼出电话拦截 --> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> <!-- 读取电话状态 --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 拨打电话 --> <uses-permission android:name="android.permission.CALL_PHONE" />