How to track the messages in Android?

夙愿已清 提交于 2019-12-20 10:49:35

问题


I want to develop an app which tracks the sent/received SMSs. I mean, when a user sends a message from its device, the message detail should be saved to a table provided by me. Similarly, when the device receives any SMS, then that also should be saved into a table provided by me.

Note that the user uses the default message application of Android to send message. I mean I am not integrating my application with the default message application. I just need to keep track of all messages sent from that application as Android keeps track of all sent messages in Sent Message folder of its Message app.

How would I do this? Please help me. I don't need answers, but I need some clue to do it.

Please don't suggest to read the messages from Inbox and Outbox etc. Because I want to save the messages when user sends/ receives it. Not after sends or receives it.


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/10910308/how-to-track-the-messages-in-android

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