How to track the messages in Android?

末鹿安然 提交于 2019-11-30 05:41:48
2red13

This is easy to do with a broadcast Receiver write in your Manifest:

edit: seems only to work for SMS_RECEIVED see this thread

<receiver android:name=".SMSReceiver"  android:enabled="true">
 <intent-filter android:priority="1000">
      <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
      <action android:name="android.provider.Telephony.SMS_SENT"/>
 </intent-filter>
</receiver>

And the Permission:

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

Then Create the Receiver llike:

public class SMSReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
       if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
    //do something with the received sms        
       }else  if(intent.getAction().equals("android.provider.Telephony.SMS_SENT")){
            //do something with the sended sms
     }
  }
}

To handle a incoming sms might look like:

Bundle extras = intent.getExtras();
Object[] pdus = (Object[]) extras.get("pdus");
for (Object pdu : pdus) {
        SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdu);
        String origin = msg.getOriginatingAddress();
        String body = msg.getMessageBody();
....
}

If you want to prevent a sms to be pushed in the commen InBox, you can achieve this with:

abortBroadcast();

Please do not call abortBroadcast() you will prevent other apps receiving the SMS_RECEIVED ordered broadcast. This is bad behavior this is not what android is about. I dont understand why google even lets developer abort broadcasts of system intents like SMS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!