android intercept blacklisted calls and text messages

In the previous blog, https://blog.csdn.net/huangbaokang/article/details/112334420

1. Manually call Service to intercept blacklist numbers

We explained how to hang up the call manually, using AIDL, and trigger the hang up function by clicking a button. Next, we realize the function of automatically hanging up the call and reaching the interception of blacklisted calls.
The specific principle is to start a service to hang up the call through the broadcast receiver, register and start the broadcast. We have two steps to manually start the hang up service. The broadcast is not used here, which will be explained later.
layout
Insert picture description here

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/btn_main_start"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="启动来电监听"
        android:onClick="startListenCall" />
    
     <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="停止来电监听"
        android:onClick="stopListenCall" 
        android:layout_below="@id/btn_main_start"
        />

</RelativeLayout>

Handling the Activity class is very simple, start the service directly, and interrupt the service

package com.hbk.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
    
    

	@Override
	protected void onCreate(Bundle savedInstanceState) {
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	public void startListenCall(View v) {
    
    
		startService(new Intent(this, ListenCallService.class));
	}
	
	public void stopListenCall(View v) {
    
    
		stopService(new Intent(this, ListenCallService.class));
	}
}

I define the ListenCallService class and use PhoneStateListener to monitor the status of different calls, focusing on handling the ringing state.

package com.hbk.service;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class ListenCallService extends Service {
    
    

	private TelephonyManager tm;
	private PhoneStateListener listener = new PhoneStateListener() {
    
    

		// 当通话状态发生改变时调用
		/**
		 * Callback invoked when device call state changes.
		 *
		 * @see TelephonyManager#CALL_STATE_IDLE
		 * @see TelephonyManager#CALL_STATE_RINGING
		 * @see TelephonyManager#CALL_STATE_OFFHOOK
		 */
		public void onCallStateChanged(int state, String incomingNumber) {
    
    
			switch (state) {
    
    
			case TelephonyManager.CALL_STATE_IDLE:// 空闲 (挂断电话/未来电之前)
				Log.e("TAG", "空闲 (挂断电话/未来电之前)");
				break;
			case TelephonyManager.CALL_STATE_RINGING:// 响铃
				Log.e("TAG", "响铃");
				// 如果来电电话是黑名单号(110), 就挂断电话
				if ("110".equals(incomingNumber)) {
    
    
					try {
    
    
						endCall();
					} catch (Exception e) {
    
    
						e.printStackTrace();
					}
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:// 接通
				Log.e("TAG", "接通");

				break;
			default:
				break;
			}
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
    
    
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 挂断电话
	 * @throws Exception 
	 */
	private void endCall() throws Exception {
    
    
		// 通过反射调用隐藏的API
		// 得到隐藏类的Class对象
		Class c = Class.forName("android.os.ServiceManager");
		// 得到方法所对应的Method对象
		Method method = c.getMethod("getService", String.class);
		// 调用方法
		IBinder iBinder = (IBinder) method.invoke(null,
				Context.TELEPHONY_SERVICE);
		// 得到接口对象
		ITelephony telephony = ITelephony.Stub.asInterface(iBinder);
		// 结束通话
		telephony.endCall();
	}

	@Override
	public void onCreate() {
    
    
		super.onCreate();
		Log.e("TAG", "Service onCreate()");

		// 得到电话管理器
		tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		// 监听电话状态
		tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public void onDestroy() {
    
    
		super.onDestroy();
		Log.e("TAG", "Service onDestroy()");
		// 停止电话监听
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);
	}

}

The above file needs to generate code based on the AIDL file before it can be referenced in ListenCallService.
Insert picture description here

The following two permissions are added to the manifest file

 	<!-- 挂断电话 -->
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <!-- 读取电话状态 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

And register the service

<service android:name="com.hbk.service.ListenCallService"></service>

Test click to start monitoring, and then make a call to 110 in the emulator, and found that there is no incoming call, but the record can be seen in the call log.
I found a giant artificial intelligence learning website a few days ago, which is easy to understand and humorous. I can’t help but share it with everyone. Click to jump to the tutorial

2. Use broadcast to intercept SMS of blacklisted numbers

Let us analyze the use of broadcasting to realize the interception of calls and text messages of blacklisted numbers.
Create a new BootReceiver to receive the receiver that is broadcast after booting

package com.hbk.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * 接收开机完成广播的receiver
 *
 */
public class BootReceiver extends BroadcastReceiver {
    
    

	@Override
	public void onReceive(Context context, Intent intent) {
    
    
		//启动电话监听的service
		context.startService(new Intent(context, ListenCallService.class));
	}

}

And add the following permissions in the manifest file

 <!-- 接收开机完成广播的权限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Register the broadcast, the action name is a fixed wording, just remember

		<receiver android:name="com.hbk.service.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

Broadcasting commonly used in work
Insert picture description here
Similarly, we define a receiver that intercepts blacklisted text messages

package com.hbk.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * 接收来了短信的广播的receiver
 *
 */
public class SmsReceiver extends BroadcastReceiver {
    
    

	@Override
	public void onReceive(Context context, Intent intent) {
    
    
		//1. 得到intent短信数据, 并封装为短信对象smsMessage
		Bundle extras = intent.getExtras();
		Object[] pdus = (Object[])extras.get("pdus");
		SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])pdus[0]);
		//2. 取号码
		String number = smsMessage.getOriginatingAddress();
		String content = smsMessage.getMessageBody();
		Log.e("TAG", number +" : "+content);
		//3. 判断是否是黑名单号
		if("110".equals(number)) {
    
    
			//4. 如果是, 中断广播(拦截短信)
			abortBroadcast();
			Log.e("TAG", "拦截到一个黑名单短信");
		}
	}

}

Configure in the manifest file

<receiver android:name="com.hbk.service.SmsReceiver">
         <intent-filter android:priority="2147483647">
             <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
         </intent-filter>
     </receiver>

Use the SmsMessage object to retrieve the phone number and text message content. To test, first deploy the application, then turn off the virtual machine, restart the test, and you can see that the broadcast receiver with the blacklisted number is in effect when you turn it on.

Guess you like

Origin blog.csdn.net/huangbaokang/article/details/112461401