Android developed the ability to capture and intercept text messages

  • 2020-11-30 08:32:43
  • OfStack

1. First of all, we need to write a broadcast receiver. When our mobile phone receives a short message, the system will send a broadcast automatically

2. In the broadcast, we rewrote the onReceive () method, and we could get the content of the text message through Bundle written by Intent.

3. We must add permission in the listing file, otherwise we cannot receive it.

4. In order to prevent us from failing to receive the broadcast, the permission of the broadcast receiver written by ourselves must be large. In case of 10000, I set 1000.

Below the code, the comments are also more detailed..


 <?xml version="." encoding="utf-"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.fanlei.cutnotedemo" >
   // Receive SMS 
   <uses-permission android:name="android.permission.RECEIVE_SMS"/>
   <application
     android:allowBackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     <!-- action:name =  The name is fixed  -->
     <receiver android:name=".NoteReceiver">
       <intent-filter android:priority="">
         <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
       </intent-filter>
     </receiver>
     <activity
       android:name=".MainActivity"
       android:label="@string/app_name" >
       <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
     </activity>
   </application>
 </manifest>

Write a class and inherit from BroadcastReceiver


Android-- Get the content of a text message and intercept it 
 package com.example.fanlei.cutnotedemo;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.telephony.SmsMessage;
 import android.widget.Toast;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 /**
 *  Broadcast receiver 
 */
 public class NoteReceiver extends BroadcastReceiver {
   private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
   @Override
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     // Judge broadcast message 
     if (action.equals(SMS_RECEIVED_ACTION)){
       Bundle bundle = intent.getExtras();
       // If it's not empty 
       if (bundle != null){
         // will pdus The content inside of it is converted to Object[] An array of 
         Object pdusData[] = (Object[]) bundle.get("pdus");
         // Parsing message 
         SmsMessage[] msg = new SmsMessage[pdusData.length];
         for (int i = ;i < msg.length;i++){
           byte pdus[] = (byte[]) pdusData[i];
           msg[i] = SmsMessage.createFromPdu(pdus);
         }
         StringBuffer content = new StringBuffer();// Get text messages 
         StringBuffer phoneNumber = new StringBuffer();// Get the address 
         StringBuffer receiveData = new StringBuffer();// To get the time 
         // Analyze the specific parameters of short message 
         for (SmsMessage temp : msg){
           content.append(temp.getMessageBody());
           phoneNumber.append(temp.getOriginatingAddress());
           receiveData.append(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
               .format(new Date(temp.getTimestampMillis())));
         }
         /**
         *  There are a lot of things we can do here, such as we block based on the phone number (cancel the broadcast and continue to spread) and so on 
         */
         Toast.makeText(context,phoneNumber.toString()+content+receiveData, Toast.LENGTH_LONG).show();// Message content 
       }
     }
   }
 }

ps: android gets all text messages


public class GetMessageInfo { 
  List<MessageInfo> list; 
  Context context; 
  MessageInfo messageInfo; 
  public GetMessageInfo(Context context) { 
    list = new ArrayList<MessageInfo>(); 
    this.context = context; 
  } 
  // -------------------------------- Text message received ---------------------------------- 
  public List<MessageInfo> getSmsInfos() { 
    final String SMS_URI_INBOX = "content://sms/inbox";//  inboxes  
    try { 
      ContentResolver cr = context.getContentResolver(); 
      String[] projection = new String[] { "_id", "address", "person","body", "date", "type" }; 
      Uri uri = Uri.parse(SMS_URI_INBOX); 
      Cursor cursor = cr.query(uri, projection, null, null, "date desc"); 
      while (cursor.moveToNext()) { 
        messageInfo = new MessageInfo(); 
        // ----------------------- information ---------------- 
        int nameColumn = cursor.getColumnIndex("person");//  Contact name list serial number  
        int phoneNumberColumn = cursor.getColumnIndex("address");//  Mobile phone no.  
        int smsbodyColumn = cursor.getColumnIndex("body");//  Message content  
        int dateColumn = cursor.getColumnIndex("date");//  The date of  
        int typeColumn = cursor.getColumnIndex("type");//  Transceiver type  1 Said to accept  2 Said to send  
        String nameId = cursor.getString(nameColumn); 
        String phoneNumber = cursor.getString(phoneNumberColumn); 
        String smsbody = cursor.getString(smsbodyColumn); 
        Date d = new Date(Long.parseLong(cursor.getString(dateColumn))); 
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd " + "\n" + "hh:mm:ss"); 
        String date = dateFormat.format(d); 
        // -------------------------- Match contact name -------------------------- 
        Uri personUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,phoneNumber); 
        Cursor localCursor = cr.query(personUri, new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.PHOTO_ID,PhoneLookup._ID }, null, null, null); 
        System.out.println(localCursor.getCount()); 
        System.out.println(" before ----"+localCursor); 
        if (localCursor.getCount()!=0) { 
          localCursor.moveToFirst(); 
          System.out.println(" after ----"+localCursor); 
          String name = localCursor.getString(localCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)); 
          long photoid = localCursor.getLong(localCursor.getColumnIndex(PhoneLookup.PHOTO_ID)); 
          long contactid = localCursor.getLong(localCursor.getColumnIndex(PhoneLookup._ID)); 
          messageInfo.setName(name); 
          //  if photoid  Is greater than 0  Indicates that the contact has an avatar   If you don't have an avatar for that person, give it to that person 1 A default  
          if (photoid > 0) { 
           Uri uri1 = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid); 
            InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri1); 
            messageInfo.setContactPhoto(BitmapFactory.decodeStream(input)); 
          } else { 
            messageInfo.setContactPhoto(BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher)); 
          } 
        }else{ 
            messageInfo.setName(phoneNumber); 
            messageInfo.setContactPhoto(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); 
          } 
        localCursor.close(); 
        messageInfo.setSmsContent(smsbody); 
        messageInfo.setSmsDate(date); 
        list.add(messageInfo); 
      } 
    } catch (SQLiteException e) { 
      e.printStackTrace(); 
    } 
    return list; 
  } 
} 

The above content is Android development of this site to share to get the content of SMS and interception, hope you like it.


Related articles: