垃圾短信拦截
在Android4.4之前,对于垃圾短信的拦截,可以通过自定义短信广播接收器,对系统的短信广播(属于有序广播)android.provider.Telephony.SMS_RECEIVED
进行接听,并将其设置为最高接听优先级(1000),然后对在黑名单中的用户发送过来的短信进行拦截(利用 abortBroadcast()函数截断广播)。具体实现方式如下:
1、AndroidManifest.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.study.sms"
android:versionCode="1"
android:versionName="1.0">
<!--声明读取短信的权限-->
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<!--静态注册自定义的接收短信的广播接收器,并设置其接收系统短信广播的优先级为最高级-1000-->
<receiver android:name=".smsReceiver">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>
2、smsReceiver的代码:
public class smsReceiver extends BroadcastReceiver {
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (SMS_RECEIVED_ACTION.equals(action)){
Bundle bundle = intent.getExtras();
if (bundle != null){
// 获取短信的内容和发送短信的地址
Object[] pdus = (Object[])bundle.get("pdus");
for (Object pdu : pdus){
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String sender = message.getOriginatingAddress();
if ("5556".equals(sender)){
//阻断广播传递,屏蔽手机号为5556的短信。
abortBroadcast();
}
}
}
}
短信机制变更
在google查阅后得知:Android为了防止第三方软件拦截短信和偷发短信吸费,在android4.4之后,只有默认的短信应用才有权限操作短信数据库。
Android4.4 之前
- 新接收短信广播 SMS_RECEIVED_ACTION为有序广播。任意应用可接到该广播并中止其继续传播。中止后优先级低的短信应用和系统短信服务将不知道新短信到达,从而不写进数据库。这样就做到了拦截(其实很多恶意应用也这么干)。
- 任意应用都可以操作短信数据库,包括新建(含伪造收件箱和发件箱短信)、修改(含篡改历史短信)、删除。
- 任意应用都可以发送短信和彩信,但默认不写进短信数据库,除非应用手动存入,否则用户是看不到的(配合拦截就可以安静地吸费了)。
Android4.4 及之后
-
设立默认短信应用机制,成为默认短信后的应用将全面接管(替代)系统短信服务。与设置默认浏览器类似,成为默认短信应用需要向用户申请。
-
新接收短信广播 SMS_RECEIVED_ACTION 更改为无序广播,增加只有默认短信应用能够接收的广播SMS_DELIVER_ACTION和WAP_PUSH_DELIVER_ACTION 。二者的不同在于,当默认短信应用收到SMS_DELIVER_ACTION 时它要负责将其存入数据库。任意应用仍然可以接收到 SMS_RECEIVED_ACTION广播但不能将其中止。因此所有的应用和系统短信服务都可以接收到新短信,没有应用能够再用中止广播的方式拦截短信。
-
只有默认短信应用可以操作短信数据库,包括新建(含伪造收件箱和发件箱短信)、修改(含篡改历史短信)和删除。其它应用只能读取短信数据库。默认短信应用需要在发送短信、收到新短信之后手动写入系统短信数据库,否则其它应用将读取不到该条短信。默认短信应用可以通过控制不写入数据库的方式拦截短信。
-
任意应用仍然都可以发送短信,但默认短信应用以外的应用发短信的接口底层改为调用系统短信服务,而不再直接调用驱动通信,因此其所发短信会被系统短信服务自动转存数据库。此外,只有默认短信应用可以发送彩信。
简单来说,第三方非默认短信应用:
- 可以收短信、发短信并接收短信回执,但是不能删除短信
- 可以查询短信数据库,但是不能新增、删除、修改短信数据库
- 无法拦截短信
短信拦截的解决方案
提示用户设置自己的app为default SMS app!!!
为了使我们的应用出现在系统设置的Default SMS app中,我们需要在Manifest中做一些声明,获取对应的权限:
- 声明一个 broadcast receiver控件,对SMS_DELIVER_ACTION广播进行监听,当然这个receiver也要声明BROADCAST_SMS权限。
- 声明一个 broadcast receiver控件,对WAP_PUSH_DELIVER_ACTION广播进行监听,当然这个receiver也要声明BROADCAST_WAP_PUSH权限。
- 在短信发送界面,需要监听 ACTION_SENDTO,同时配置上sms:, smsto:, mms:, and mmsto这四个概要,这样别的应用如果想发送短信,你的这个activity就能知道。
- 需要有一个service,能够监听ACTION_RESPONSE_VIA_MESSAGE,同时也要配置上sms:, smsto:, mms:, and mmsto这四个概要,并且要声明SEND_RESPOND_VIA_MESSAGE权限。这样用户就能在来电的时候,用你的应用来发送拒绝短信。
<manifest>
...
<application>
<!-- BroadcastReceiver that listens for incoming SMS messages -->
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<!-- BroadcastReceiver that listens for incoming MMS messages -->
<receiver android:name=".MmsReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<!-- Activity that allows the user to send new SMS/MMS messages -->
<activity android:name=“.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</activity>
<!-- Service that delivers messages from the phone "quick response" -->
<service android:name=".HeadlessSmsSendService"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
</application>
</manifest>
通过 Telephony.Sms.getDefaultSmsPackage()方法来判断自己的应用是否为Default SMS app。如果不是,可以通过startActivity() 方法启动类似如下的Dialog。
public class MainActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
final String myPackageName = getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
// App is not default.
// Show the "not currently set as the default SMS app" interface
View viewGroup = findViewById(R.id.ll_not_default_app);
viewGroup.setVisibility(View.VISIBLE);
// Set up a button that allows the user to change the default SMS app
View button = findViewById(R.id.btn_change_default_app);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
startActivity(intent);
}
});
} else {
// App is the default.
// Hide the "not currently set as the default SMS app" interface
View viewGroup = findViewById(R.id.ll_not_default_app);
viewGroup.setVisibility(View.GONE);
}
}
以上源码下载地址:https://github.com/wenzhiming/520sms
骚扰电话拦截
在很多手机卫士或者通讯卫士里面都有一项实用的功能,那就是拦截已加入黑名单之中的电话,那么这个功能是如何实现的呢?现在就让我们来看看吧。
我们先看代码,然后再解释其中的意思吧。我们需要监听来电,当有电话打过来的时候马上执行拦截电话的方法,所以要把拦截电话的功能放在Service之中。
完整的拦截电话服务代码如下:
public class EndCallService extends Service {
// 电话管理的对象
private TelephonyManager telephonyManager;
// 自定义的电话状态监听器
private MyPhoneStateListener myPhoneStateListener;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// 监听电话状态
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
myPhoneStateListener = new MyPhoneStateListener();
// 参数1:监听;参数2:监听的事件
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, final String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
// 如果是响铃状态,检测拦截模式是否是电话拦截,是挂断
if (state == TelephonyManager.CALL_STATE_RINGING) {
// 挂断电话
endCall();
// 删除通话记录
// 1.获取内容解析者
final ContentResolver resolver = getContentResolver();
// 2.获取内容提供者地址 call_log calls表的地址:calls
// 3.获取执行操作路径
final Uri uri = Uri.parse("content://call_log/calls");
// 4.删除操作
// 通过内容观察者观察内容提供者内容,如果变化,就去执行删除操作
// notifyForDescendents : 匹配规则,true : 精确匹配 false:模糊匹配
resolver.registerContentObserver(uri, true, new ContentObserver(new Handler()) {
// 内容提供者内容变化的时候调用
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// 删除通话记录
resolver.delete(uri, "number=?", new String[] { incomingNumber });
// 注销内容观察者
resolver.unregisterContentObserver(this);
}
});
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
/**
* 挂断电话
*/
public void endCall() {
//通过反射进行实现
try {
//1.通过类加载器加载相应类的class文件。反射调用,获取ServiceManager字节码文件,需要类的完整的路径
Class<?> forName = Class.forName("android.os.ServiceManager");
//2.获取类中相应的方法
Method method = loadClass.getDeclaredMethod("getService", String.class);
//3.执行方法,获取返回值
IBinder invoke = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE);
//4.调用获取aidl文件对象方法
ITelephony iTelephony = ITelephony.Stub.asInterface(invoke);
//5.调用在aidl中隐藏的endCall方法挂断电话
iTelephony.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
}
实现过程中主要问题为接口ITelephony,是Android系统Phone类中TelephonyManager提供给上层应用程序用户与telephony进行操作交互的接口。必须通过AIDL(Android Interface Definition Language,即Android接口定义语言)。
Android没有对外公开结束通话的API,要结束通话就必须使用AIDL与电话管理服务进行通信,并调用服务中的API实现结束通话,这样需要android 源码文件ITelephony.aidl添加到项目中,如图所示:
ITelephony.aidl的代码如下:
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.os.Bundle;
import java.util.List;
import android.telephony.NeighboringCellInfo;
/**
* Interface used to interact with the phone. Mostly this is used by the
* TelephonyManager class. A few places are still using this directly.
* Please clean them up if possible and use TelephonyManager insteadl.
*
* {@hide}
*/
interface ITelephony {
/**
* Dial a number. This doesn't place the call. It displays
* the Dialer screen.
* @param number the number to be dialed. If null, this
* would display the Dialer screen with no number pre-filled.
*/
void dial(String number);
/**
* Place a call to the specified number.
* @param number the number to be called.
*/
void call(String number);
/**
* If there is currently a call in progress, show the call screen.
* The DTMF dialpad may or may not be visible initially, depending on
* whether it was up when the user last exited the InCallScreen.
*
* @return true if the call screen was shown.
*/
boolean showCallScreen();
/**
* Variation of showCallScreen() that also specifies whether the
* DTMF dialpad should be initially visible when the InCallScreen
* comes up.
*
* @param showDialpad if true, make the dialpad visible initially,
* otherwise hide the dialpad initially.
* @return true if the call screen was shown.
*
* @see showCallScreen
*/
boolean showCallScreenWithDialpad(boolean showDialpad);
/**
* End call or go to the Home screen
*
* @return whether it hung up
*/
boolean endCall();
/**
* Answer the currently-ringing call.
*
* If there's already a current active call, that call will be
* automatically put on hold. If both lines are currently in use, the
* current active call will be ended.
*
* TODO: provide a flag to let the caller specify what policy to use
* if both lines are in use. (The current behavior is hardwired to
* "answer incoming, end ongoing", which is how the CALL button
* is specced to behave.)
*
* TODO: this should be a oneway call (especially since it's called
* directly from the key queue thread).
*/
void answerRingingCall();
/**
* Silence the ringer if an incoming call is currently ringing.
* (If vibrating, stop the vibrator also.)
*
* It's safe to call this if the ringer has already been silenced, or
* even if there's no incoming call. (If so, this method will do nothing.)
*
* TODO: this should be a oneway call too (see above).
* (Actually *all* the methods here that return void can
* probably be oneway.)
*/
void silenceRinger();
/**
* Check if we are in either an active or holding call
* @return true if the phone state is OFFHOOK.
*/
boolean isOffhook();
/**
* Check if an incoming phone call is ringing or call waiting.
* @return true if the phone state is RINGING.
*/
boolean isRinging();
/**
* Check if the phone is idle.
* @return true if the phone state is IDLE.
*/
boolean isIdle();
/**
* Check to see if the radio is on or not.
* @return returns true if the radio is on.
*/
boolean isRadioOn();
/**
* Check if the SIM pin lock is enabled.
* @return true if the SIM pin lock is enabled.
*/
boolean isSimPinEnabled();
/**
* Cancels the missed calls notification.
*/
void cancelMissedCallsNotification();
/**
* Supply a pin to unlock the SIM. Blocks until a result is determined.
* @param pin The pin to check.
* @return whether the operation was a success.
*/
boolean supplyPin(String pin);
/**
* Handles PIN MMI commands (PIN/PIN2/PUK/PUK2), which are initiated
* without SEND (so <code>dial</code> is not appropriate).
*
* @param dialString the MMI command to be executed.
* @return true if MMI command is executed.
*/
boolean handlePinMmi(String dialString);
/**
* Toggles the radio on or off.
*/
void toggleRadioOnOff();
/**
* Set the radio to on or off
*/
boolean setRadio(boolean turnOn);
/**
* Request to update location information in service state
*/
void updateServiceLocation();
/**
* Enable location update notifications.
*/
void enableLocationUpdates();
/**
* Disable location update notifications.
*/
void disableLocationUpdates();
/**
* Enable a specific APN type.
*/
int enableApnType(String type);
/**
* Disable a specific APN type.
*/
int disableApnType(String type);
/**
* Allow mobile data connections.
*/
boolean enableDataConnectivity();
/**
* Disallow mobile data connections.
*/
boolean disableDataConnectivity();
/**
* Report whether data connectivity is possible.
*/
boolean isDataConnectivityPossible();
Bundle getCellLocation();
/**
* Returns the neighboring cell information of the device.
*/
List<NeighboringCellInfo> getNeighboringCellInfo();
int getCallState();
int getDataActivity();
int getDataState();
/**
* Returns the current active phone type as integer.
* Returns TelephonyManager.PHONE_TYPE_CDMA if RILConstants.CDMA_PHONE
* and TelephonyManager.PHONE_TYPE_GSM if RILConstants.GSM_PHONE
*/
int getActivePhoneType();
/**
* Returns the CDMA ERI icon index to display
*/
int getCdmaEriIconIndex();
/**
* Returns the CDMA ERI icon mode,
* 0 - ON
* 1 - FLASHING
*/
int getCdmaEriIconMode();
/**
* Returns the CDMA ERI text,
*/
String getCdmaEriText();
/**
* Returns true if CDMA provisioning needs to run.
*/
boolean getCdmaNeedsProvisioning();
/**
* Returns the unread count of voicemails
*/
int getVoiceMessageCount();
/**
* Returns the network type
*/
int getNetworkType();
/**
* Return true if an ICC card is present
*/
boolean hasIccCard();
}
手机通讯卫士
以下代码展示如何拦截垃圾短信(Android4.4之前,已失效)和拦截骚扰电话(可用):
/**
* FileName: InterceptService <br>
* Description: 通讯卫士模块的黑名单电话和短信拦截服务 <br>
* Author: Tr0e <br>
* Date: 2019/4/28 15:59
*/
public class InterceptService extends Service {
private static final String tag = "InterceptService";
// 自定义的拦截短信的广播接收器
private InnerSmsReceiver mInnerSmsReceiver;
// 操作黑名单列表数据的对象
private BlackNumberDao mBlackNumberDao;
// 电话管理的对象
private TelephonyManager mTelephonyManager;
// 自定义的电话状态监听器
private MyPhoneStateListener myPhoneStateListener;
// 内容观察者对象
private MyContentObserver mMyContentObserver;
@Override
public void onCreate() {
// 获取操作黑名单列表数据的对象
mBlackNumberDao = BlackNumberDao.getInstance(getApplicationContext());
// 获取电话管理者对象
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// 创建自定义的电话状态监听器
myPhoneStateListener = new MyPhoneStateListener();
// 监听电话来电状态
mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
// 拦截短信的过滤器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
// 设置优先级为最高
intentFilter.setPriority(Integer.MAX_VALUE);
mInnerSmsReceiver = new InnerSmsReceiver();
// 注册自定义的拦截短信的广播接收器
registerReceiver(mInnerSmsReceiver, intentFilter);
super.onCreate();
}
class MyPhoneStateListener extends PhoneStateListener {
// 重写电话状态改变时触发的方法
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.i(tag, "响铃" + incomingNumber);
// 响铃之后挂断电话
endCall(incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(tag, "接听");
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(tag, "挂断");
break;
}
}
}
/**
* 响铃之后挂断电话
*/
private void endCall(String phoneNumber) {
//从本地数据库读取来电号码被设置的拦截模式
int mode = mBlackNumberDao.getMode(phoneNumber);
// 判断获取的拦截模式,若为1和3则拦截
if (mode == 1 || mode == 3) {
try {
// 反射调用
// 获取ServiceManager字节码文件,需要类的完整的路径
Class<?> clazz = Class.forName("android.os.ServiceManager");
// 获取方法
Method method = clazz.getMethod("getService", String.class);
// 反射调用此方法
IBinder iBinder = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE);
// 调用获取aidl文件对象方法
ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
// 调用在aidl中隐藏的endCall方法自动挂掉电话,来电者将收到提示“您拨打的号码正在通话中!”
iTelephony.endCall();
} catch (Exception e) {
e.printStackTrace();
}
// 创建内容观察者,并注册
mMyContentObserver = new MyContentObserver(new Handler(), phoneNumber);
getContentResolver().registerContentObserver(Uri.parse("content://call_log/calls"), true, mMyContentObserver);
}
}
/**
* 该内容观察者类的目的在于拦截到垃圾电话后,将黑名单号码的相应的通话记录在手机本地缓存中删除
*/
class MyContentObserver extends ContentObserver {
String phoneNumber;
/**
* 创建一个内容观察者对象,用于将黑名单号码的相应的通话记录在手机本地缓存中删除
*
* @param handler The handler to run {@link #onChange} on, or null if none.
* @param phoneNumber 被拦截的电话号码
*/
public MyContentObserver(Handler handler, String phoneNumber) {
super(handler);
this.phoneNumber = phoneNumber;
}
// 内容观察者若是观察到数据库中数据有变化时,调用此方法
@Override
public void onChange(boolean selfChange) {
getContentResolver().delete(Uri.parse("content://call_log/calls"), "number = ?", new String[]{phoneNumber});
super.onChange(selfChange);
}
}
class InnerSmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 获取短信的内容和发送短信的地址
Object[] messages = (Object[]) intent.getExtras().get("pdus");
// 循环遍历获取到的短信内容
for (Object message : messages) {
// 获取短信对象
SmsMessage sms = SmsMessage.createFromPdu((byte[]) message);
// 获取短信对象的基本信息,发短信的号码,短信内容
String messageAdressNum = sms.getOriginatingAddress();
Log.i(tag, "messageAdressNum:" + messageAdressNum);
String messageBody = sms.getMessageBody();
int mode = mBlackNumberDao.getMode(messageAdressNum);
Log.i(tag, "mode:" + mode);
// 获取到发送短信的号码,也能查到拦截模式,但是没法拦截短信,待解决???
// 如果黑名单中该电话号码的拦截模式满足以下条件则阻断广播传递
// 解决:拦截短信(android 4.4版本失效)
if (mode == 2 || mode == 3) {
abortBroadcast();
}
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// 服务结束时,取消注册自定义的拦截短信的广播接收器
if (mInnerSmsReceiver != null) {
unregisterReceiver(mInnerSmsReceiver);
}
// 服务结束时,注销内容观察者
if (mMyContentObserver != null) {
getContentResolver().unregisterContentObserver(mMyContentObserver);
}
// 服务结束时,取消电话状态的监听
if (myPhoneStateListener != null) {
mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
}
}