SoFunction
Updated on 2025-04-08

Android projects achieve blacklist interception effect

This article describes the implementation method of blacklisting in Android programming. Share it for your reference, as follows:

1. Blacklist database creation

Three fields (_id self-growth field phone blacklist number mode intercept type)

SQL statement for creating table

create table blacknumber (_id integer primary key autoincrement , phone varchar(20), mode varchar(5));

Combine the project to create a database and corresponding tables

BlackNumberDao singleton mode

package .;

import ;
import ;

import ;
import ;
import ;
import ;

import .;
import .;

public class BlackNumberDao {
  private BlackNumberOpenHelper blackNumberOpenHelper;
  //BlackNumberDao singleton mode  //1,Privacy construction method  private BlackNumberDao(Context context){
    //Create the database and its table organization    blackNumberOpenHelper = new BlackNumberOpenHelper(context);
  }
  //2, declare an object of the current class  private static BlackNumberDao blackNumberDao = null;
  //3, provide a static method, if the object of the current class is empty, create a new one  public static BlackNumberDao getInstance(Context context){
    if(blackNumberDao == null){
      blackNumberDao = new BlackNumberDao(context);
    }
    return blackNumberDao;
  }
  
  /**Add an entry
    * @param phone blocked phone number
    * @param mode Intercept type (1: SMS 2: Phone 3: Intercept all (SMS + Phone))
    */
  public void insert(String phone,String mode){
    //1, enable the database and prepare to do the write operation    SQLiteDatabase db = ();

    ContentValues values = new ContentValues();
    ("phone", phone);
    ("mode", mode);
    ("blacknumber", null, values);
    
    ();
  }
  
  /**Remove a phone number from the database
    * @param phone Delete phone number
    */
  public void delete(String phone){
    SQLiteDatabase db = ();

    ("blacknumber", "phone = ?", new String[]{phone});
    
    ();
  }
  
  /**
    * Go according to phone number, update the interception mode
    * @param phone Update the phone number of blocking mode
    * @param mode to update to (1: SMS 2: Phone 3: Intercept all (SMS + Phone)
    */
  public void update(String phone,String mode){
    SQLiteDatabase db = ();

    ContentValues contentValues = new ContentValues();
    ("mode", mode);
    
    ("blacknumber", contentValues, "phone = ?", new String[]{phone});
    
    ();
  }
  
  /**
    * @return Query all numbers in the database and the collection where the intercept type resides
    */
  public List<BlackNumberInfo> findAll(){
    SQLiteDatabase db = ();

    Cursor cursor = ("blacknumber", new String[]{"phone","mode"}, null, null, null, null, "_id desc");
    List<BlackNumberInfo> blackNumberList = new ArrayList<BlackNumberInfo>();
    while(()){
      BlackNumberInfo blackNumberInfo = new BlackNumberInfo();
       = (0);
       = (1);
      (blackNumberInfo);
    }
    ();
    ();
    
    return blackNumberList;
  }
  
  /**
    * 20 pieces of data are searched each time
    * @param index query index value
    */
  public List<BlackNumberInfo> find(int index){
    SQLiteDatabase db = ();

    Cursor cursor = ("select phone,mode from blacknumber order by _id desc limit ?,20;", new String[]{index+""});
    
    List<BlackNumberInfo> blackNumberList = new ArrayList<BlackNumberInfo>();
    while(()){
      BlackNumberInfo blackNumberInfo = new BlackNumberInfo();
       = (0);
       = (1);
      (blackNumberInfo);
    }
    ();
    ();
    
    return blackNumberList;
  }
  
  /**
    * @return The total number of entries of data in the database, returning 0 means no data or exception
    */
  public int getCount(){
    SQLiteDatabase db = ();
    int count = 0;
    Cursor cursor = ("select count(*) from blacknumber;", null);
    if(()){
      count = (0);
    }
    
    ();
    ();
    return count;
  }
  
  /**
    * @param phone number as query criteria
    * @return Intercept mode of incoming phone number 1: SMS 2: Phone 3: All 0: No data
    */
  public int getMode(String phone){
    SQLiteDatabase db = ();
    int mode = 0;
    Cursor cursor = ("blacknumber", new String[]{"mode"}, "phone = ?", new String[]{phone}, null, null,null);
    if(()){
      mode = (0);
    }
    
    ();
    ();
    return mode;
  }
}

3. Load more trigger conditions

  1. Listening status changes
  2. Scroll to the bottom, and the last listView entry is visible
  3. The scrolling state changes. Scroll------>Stop (idle)

After loading the next page of data, it needs to be added to the end of the previous page of data.

// Listen to its scrolling statuslv_blacknumber.setOnScrollListener(new OnScrollListener() {
  //During the scrolling process, the state changes and call method()  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
// OnScrollListener.SCROLL_STATE_FLING Scroll quickly// OnScrollListener.SCROLL_STATE_IDLE Idle status// OnScrollListener.SCROLL_STATE_TOUCH_SCROLL Touch and scroll state     
    if(mBlackNumberList!=null){
      //Condition 1: Scroll to stop state      //Condition 2: The last entry is visible (the index value of the last entry >=The total number of entries in the data adapter -1)      if(scrollState == OnScrollListener.SCROLL_STATE_IDLE
          && lv_blacknumber.getLastVisiblePosition()>=()-1
          && !mIsLoad){
        /*mIsLoad prevents repeated loading of variables
         If mIsLoad is currently loading, it will be true. After this loading is completed, change mIsLoad to false
         If the next load needs to be executed, it will determine whether the appeal mIsLoad variable is false. If true, you need to wait for the last load to complete and put its value into consideration.
         Change to false and then load */
         
        //If the total number of entries is greater than the collection size, you can continue to load more        if(mCount>()){
          //Load the next page of data          new Thread(){
            public void run() {
              //1, get the object of the operation blacklist database              mDao = (getApplicationContext());
              //2, query some data              List<BlackNumberInfo> moreData = (());
              //3, the process of adding data on the next page              (moreData);
              //4, notify the data adapter to refresh              (0);
            }
          }.start();
        }
      }
    }
     
  }
   
  //Calling method during scrolling  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {
     
  }
});

4. Intercept text messages

When receiving a text message, it will broadcast it, monitor the broadcast recipient, and intercept the text message (orderly)
Increase broadcast priority level to the highest (1000)

5. Intercept the phone number

There is a phone dialing in, and it is in a ringing state. The phone is hung up through the code (aidl, reflection) and intercepted the phone.
The method of hanging up the phone number is placed in the aidl file with the name endCall

Check the TelePhoneManager source code here and find a way to obtain ITelephony objects

ServiceManager androids are hidden from developers, so they cannot directly call their methods, so they need to reflective calls.

((Context.TELEPHONY_SERVICE));

<uses-permission android:name=".CALL_PHONE"/>

//1, get the ServiceManager bytecode fileClass<?> clazz = ("");
//2, get methodMethod method = ("getService", );
//3, Reflection calls this methodIBinder iBinder = (IBinder) (null, Context.TELEPHONY_SERVICE);
//4, call the method to obtain the aidl file objectITelephony iTelephony = (iBinder);
//5, call the endCall method hidden in aidl

BlackNumberService

();
package .;

import ;
import ;

import ;
import .;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class BlackNumberService extends Service {
  private InnerSmsReceiver mInnerSmsReceiver;
  private BlackNumberDao mDao;
  private TelephonyManager mTM;
  private MyPhoneStateListener mPhoneStateListener;
  @Override
  public void onCreate() {
    mDao = (getApplicationContext());
    
    //Intercept SMS    IntentFilter intentFilter = new IntentFilter();
    (".SMS_RECEIVED");
    (1000);
    
    mInnerSmsReceiver = new InnerSmsReceiver();
    registerReceiver(mInnerSmsReceiver, intentFilter);
    
    //The status of the monitored phone    //1, Telephone Manager object    mTM = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    //2, monitor the phone status    mPhoneStateListener = new MyPhoneStateListener();
    (mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    
    ();
  }
  
  class MyPhoneStateListener extends PhoneStateListener{
    //3, manual rewrite, method to trigger if the phone status changes if it changes, the method will be triggered    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
      switch (state) {
      case TelephonyManager.CALL_STATE_IDLE:
        break;
      case TelephonyManager.CALL_STATE_OFFHOOK:
        break;
      case TelephonyManager.CALL_STATE_RINGING:
        //Hang up the phone and went to the aidl file//        ();
        endCall(incomingNumber);
        break;
      }
      (state, incomingNumber);
    }
  }
  class InnerSmsReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
      //Get the text message content and get the sending text message phone number. If this phone number is on the blacklist and the interception mode is also 1 (SMS) or 3 (all), intercept the text message.      //1, get text message content      Object[] objects = (Object[]) ().get("pdus");
      //2, loop through the SMS process      for (Object object : objects) {
        //3, get the SMS object        SmsMessage sms = ((byte[])object);
        //4, get basic information about the SMS object        String originatingAddress = ();
        String messageBody = ();
        
        int mode = (originatingAddress);
        
        if(mode == 1 || mode == 3){
          //Intercept SMS (android 4.4 version invalid SMS database, deleted)          abortBroadcast();
        }
      }
    }
  }
  
  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }
  public void endCall(String phone) {
    int mode = (phone);
    
    if(mode == 2 || mode == 3){
//      ((Context.TELEPHONY_SERVICE));
      //An android like ServiceManager is hidden from developers, so it cannot directly call its methods, and it needs to be called reflectively.      try {
        //1, get the ServiceManager bytecode file        Class<?> clazz = ("");
        //2, get method        Method method = ("getService", );
        //3, Reflection calls this method        IBinder iBinder = (IBinder) (null, Context.TELEPHONY_SERVICE);
        //4, call the method to obtain the aidl file object        ITelephony iTelephony = (iBinder);
        //5, call the endCall method hidden in aidl        ();
      } catch (Exception e) {
        ();
      }
    }
  }
  @Override
  public void onDestroy() {
    if(mInnerSmsReceiver!=null){
      unregisterReceiver(mInnerSmsReceiver);
    }
    ();
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.