Android parses SMS messages

Source: Internet
Author: User

Recently, a project needs to parse text messages on a mobile phone. There are two ways to get text messages: one is to broadcast messages, and the other is to use a database. Because the project requires me to select the second method, retrieve the text message from the database to obtain the text message information and parse the specified content.

When creating any new feature, Let's first look at the relevant knowledge, and then see if there is any related demo. Finally, we suggest reading the Android Application Layer source code in turn, let's take a look at some constant definitions in it. We recommend that you use a later version of api. You may not be able to use it, but it will give you some ideas. Take the text message function as an example:

Now that we want to get the text message information, we need to go to android. provider. Telephony in android. jar as long as it consists of various components. We can see the related attributes of Sms. If you call this content, the Field requires API level 19 (current min is) will be prompted, but this does not prevent us from imitating it. What I need is to retrieve the inbox, therefore, when searching for a database, I only need to search for text messages in the inbox. In Telephony, the Message type in the TextBasedSmsColumns interface is MESSAGE_TYPE_INBOX. Next, let's take a look at the Sms interface:

/**     * Contains all text-based SMS messages.     */    public static final class Sms implements BaseColumns, TextBasedSmsColumns {        /**         * Not instantiable.         * @hide         */        private Sms() {        }        /**         * Used to determine the currently configured default SMS package.         * @param context context of the requesting application         * @return package name for the default SMS package or null         */        public static String getDefaultSmsPackage(Context context) {            ComponentName component = SmsApplication.getDefaultSmsApplication(context, false);            if (component != null) {                return component.getPackageName();            }            return null;        }        /**         * Return cursor for table query.         * @hide         */        public static Cursor query(ContentResolver cr, String[] projection) {            return cr.query(CONTENT_URI, projection, null, null, DEFAULT_SORT_ORDER);        }        /**         * Return cursor for table query.         * @hide         */        public static Cursor query(ContentResolver cr, String[] projection,                String where, String orderBy) {            return cr.query(CONTENT_URI, projection, where,                    null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);        }        /**         * The {@code content://} style URL for this table.         */        public static final Uri CONTENT_URI = Uri.parse("content://sms");        /**         * The default sort order for this table.         */        public static final String DEFAULT_SORT_ORDER = "date DESC";        /**         * Add an SMS to the given URI.         *         * @param resolver the content resolver to use         * @param uri the URI to add the message to         * @param address the address of the sender         * @param body the body of the message         * @param subject the pseudo-subject of the message         * @param date the timestamp for the message         * @param read true if the message has been read, false if not         * @param deliveryReport true if a delivery report was requested, false if not         * @return the URI for the new message         * @hide         */        public static Uri addMessageToUri(ContentResolver resolver,                Uri uri, String address, String body, String subject,                Long date, boolean read, boolean deliveryReport) {            return addMessageToUri(resolver, uri, address, body, subject,                    date, read, deliveryReport, -1L);        }        /**         * Add an SMS to the given URI with the specified thread ID.         *         * @param resolver the content resolver to use         * @param uri the URI to add the message to         * @param address the address of the sender         * @param body the body of the message         * @param subject the pseudo-subject of the message         * @param date the timestamp for the message         * @param read true if the message has been read, false if not         * @param deliveryReport true if a delivery report was requested, false if not         * @param threadId the thread_id of the message         * @return the URI for the new message         * @hide         */        public static Uri addMessageToUri(ContentResolver resolver,                Uri uri, String address, String body, String subject,                Long date, boolean read, boolean deliveryReport, long threadId) {            ContentValues values = new ContentValues(7);            values.put(ADDRESS, address);            if (date != null) {                values.put(DATE, date);            }            values.put(READ, read ? Integer.valueOf(1) : Integer.valueOf(0));            values.put(SUBJECT, subject);            values.put(BODY, body);            if (deliveryReport) {                values.put(STATUS, STATUS_PENDING);            }            if (threadId != -1L) {                values.put(THREAD_ID, threadId);            }            return resolver.insert(uri, values);        }        /**         * Move a message to the given folder.         *         * @param context the context to use         * @param uri the message to move         * @param folder the folder to move to         * @return true if the operation succeeded         * @hide         */        public static boolean moveMessageToFolder(Context context,                Uri uri, int folder, int error) {            if (uri == null) {                return false;            }            boolean markAsUnread = false;            boolean markAsRead = false;            switch(folder) {            case MESSAGE_TYPE_INBOX:            case MESSAGE_TYPE_DRAFT:                break;            case MESSAGE_TYPE_OUTBOX:            case MESSAGE_TYPE_SENT:                markAsRead = true;                break;            case MESSAGE_TYPE_FAILED:            case MESSAGE_TYPE_QUEUED:                markAsUnread = true;                break;            default:                return false;            }            ContentValues values = new ContentValues(3);            values.put(TYPE, folder);            if (markAsUnread) {                values.put(READ, 0);            } else if (markAsRead) {                values.put(READ, 1);            }            values.put(ERROR_CODE, error);            return 1 == SqliteWrapper.update(context, context.getContentResolver(),                            uri, values, null, null);        }        /**         * Returns true iff the folder (message type) identifies an         * outgoing message.         * @hide         */        public static boolean isOutgoingFolder(int messageType) {            return  (messageType == MESSAGE_TYPE_FAILED)                    || (messageType == MESSAGE_TYPE_OUTBOX)                    || (messageType == MESSAGE_TYPE_SENT)                    || (messageType == MESSAGE_TYPE_QUEUED);        }

The query function and add function are provided. Because I only need the query function, the public static final Uri CONTENT_URI = Uri. parse ("content: // sms"); indicates that all messages are queried, and I only need to query the messages in the inbox, so the above is changed to public static final Uri CONTENT_URI = Uri. parse ("content: // sms/inbox"); copy the content of the Sms and TextBasedSmsColumns interfaces and place them in the two interfaces respectively to name them and set them by yourself. In Sms, some errors are reported, some of the methods that are not open to the system are referenced to delete irrelevant Code. The Code after sorting is as follows:

package com.jwzhangjie.smarttv_client.support.sms1;import android.content.ContentResolver;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.provider.BaseColumns;public final class Sms implements BaseColumns, TextBasedSmsColumns{ /**     * Not instantiable.     * @hide     */    private Sms() {    }    /**     * Return cursor for table query.     * @hide     */    public static Cursor query(ContentResolver cr, String[] projection) {        return cr.query(CONTENT_URI, projection, null, null, DEFAULT_SORT_ORDER);    }    /**     * Return cursor for table query.     * @hide     */    public static Cursor query(ContentResolver cr, String[] projection,            String where, String orderBy) {        return cr.query(CONTENT_URI, projection, where,                null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);    }    /**     * The {@code content://} style URL for this table.     *///    public static final Uri CONTENT_URI = Uri.parse("content://sms");    public static final Uri CONTENT_URI = Uri.parse("content://sms/inbox");    /**     * The default sort order for this table.     */    public static final String DEFAULT_SORT_ORDER = "date DESC";    /**     * Add an SMS to the given URI.     *     * @param resolver the content resolver to use     * @param uri the URI to add the message to     * @param address the address of the sender     * @param body the body of the message     * @param subject the pseudo-subject of the message     * @param date the timestamp for the message     * @param read true if the message has been read, false if not     * @param deliveryReport true if a delivery report was requested, false if not     * @return the URI for the new message     * @hide     */    public static Uri addMessageToUri(ContentResolver resolver,            Uri uri, String address, String body, String subject,            Long date, boolean read, boolean deliveryReport) {        return addMessageToUri(resolver, uri, address, body, subject,                date, read, deliveryReport, -1L);    }    /**     * Add an SMS to the given URI with the specified thread ID.     *     * @param resolver the content resolver to use     * @param uri the URI to add the message to     * @param address the address of the sender     * @param body the body of the message     * @param subject the pseudo-subject of the message     * @param date the timestamp for the message     * @param read true if the message has been read, false if not     * @param deliveryReport true if a delivery report was requested, false if not     * @param threadId the thread_id of the message     * @return the URI for the new message     * @hide     */    public static Uri addMessageToUri(ContentResolver resolver,            Uri uri, String address, String body, String subject,            Long date, boolean read, boolean deliveryReport, long threadId) {        ContentValues values = new ContentValues(7);        values.put(ADDRESS, address);        if (date != null) {            values.put(DATE, date);        }        values.put(READ, read ? Integer.valueOf(1) : Integer.valueOf(0));        values.put(SUBJECT, subject);        values.put(BODY, body);        if (deliveryReport) {            values.put(STATUS, STATUS_PENDING);        }        if (threadId != -1L) {            values.put(THREAD_ID, threadId);        }        return resolver.insert(uri, values);    }    /**     * Returns true iff the folder (message type) identifies an     * outgoing message.     * @hide     */    public static boolean isOutgoingFolder(int messageType) {        return  (messageType == MESSAGE_TYPE_FAILED)                || (messageType == MESSAGE_TYPE_OUTBOX)                || (messageType == MESSAGE_TYPE_SENT)                || (messageType == MESSAGE_TYPE_QUEUED);}}


The above code will not be wrong. After the query function is available, we need to write a class to save the queried content and write it according to our own project. For example:

Package com. jwzhangjie. smarttv_client.support.sms1;/*** sms-related fields in the database are as follows: _ id: An auto-increment field, with thread_id serial number starting from 1, the id of the same sender is the serial number in the contact list of the sender's mobile phone number in the same address. The stranger is the null date sending date protocol, which is divided into: 0 SMS_RPOTO, 1 MMS_PROTO read whether read 0 unread, 1 read status-1 received, 0 complete, 64 pending, 128 failed type ALL = 0; INBOX = 1; SENT = 2; DRAFT = 3; OUTBOX = 4; FAILED = 5; QUEUED = 6; body text message content service_center text message service center number subject text message subject reply_path_present TP-Reply-Path locked */import android. OS. parcel; import android. OS. parcelable;/*** Save the message ** @ author ~zhangjie **/public class SMSInfo implements Parcelable {@ Overridepublic int describeContents () {return 0 ;} /*** SMS no. */private long id;/*** protocol 0: SMS_PROTO SMS 1: MMS_PROTO MMS */private int protocol; /***** text message content */private String smsBody;/***** phone number for Sending Short Messages */private String smsPhoneNum; /*** date and time when the SMS is sent */private String smsDateTime;/***** sender */private String smsSender;/*** SMS type: 1 is received 2 is sent */private int smsType; public SMSInfo () {} private SMSInfo (Parcel source) {readFromParcel (source );} public void readFromParcel (Parcel source) {id = source. readLong (); protocol = source. readInt (); smsBody = source. readString (); smsPhoneNum = source. readString (); smsDateTime = source. readString (); smsSender = source. readString (); smsType = source. readInt () ;}@ Overridepublic void writeToParcel (Parcel dest, int flags) {dest. writeLong (id); dest. writeInt (protocol); dest. writeString (smsBody); dest. writeString (smsPhoneNum); dest. writeString (smsDateTime); dest. writeString (smsSender); dest. writeInt (smsType);} public static Creator
 
  
CREATOR = new Creator
  
   
() {@ Overridepublic SMSInfo createFromParcel (Parcel source) {return new SMSInfo (source) ;}@ Overridepublic SMSInfo [] newArray (int size) {return new SMSInfo [size] ;};@ Overridepublic String toString () {StringBuilder builder = new StringBuilder (); builder. append ("id:" + id + "protocol:" + protocol + "content:" + smsBody); return builder. toString ();} public long getId () {return id;} public void setId (long id) {this. id = id;} public int getProtocol () {return protocol;} public void setProtocol (int protocol) {this. protocol = protocol;} public String getSmsBody () {return smsBody;} public void setSmsBody (String smsBody) {this. smsBody = smsBody;} public String getSmsPhoneNum () {return smsPhoneNum;} public void setSmsPhoneNum (String smsPhoneNum) {this. smsPhoneNum = smsPhoneNum;} public String getSmsDateTime () {return smsDateTime;} public void setSmsDateTime (String smsDateTime) {this. smsDateTime = smsDateTime;} public String getSmsSender () {return smsSender;} public void setSmsSender (String smsSender) {this. smsSender = smsSender;} public int getSmsType () {return smsType;} public void setSmsType (int smsType) {this. smsType = smsType ;}}
  
 


The next step is to get the database content. Let's first look at the database query method:

 /**     * Return cursor for table query.     * @hide     */    public static Cursor query(ContentResolver cr, String[] projection,            String where, String orderBy) {        return cr.query(CONTENT_URI, projection, where,                null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);    }


CONTENT_URI: The public static final Uri CONTENT_URI = Uri. parse ("content: // sms/inbox") defined above ");

Projection: this can be null, that is, getting all columns, but you don't have to. You can get whatever you need. Otherwise, it will waste both time and memory.

Where: Query Condition

OrderBy: Sort

Package com. jwzhangjie. smarttv_client.support.sms1; import java. util. arrayList; import java. util. list; import android. content. contentResolver; import android. content. context; import android. database. cursor; public class GetSMSInfo {private ContentResolver mResolver; private Context context; private List
 
  
Infos; private static final String [] PROJECTION = new String [] {Sms. _ ID, // 0: as a flag, record the last one as the first Sms for the next scan. TYPE, // 1: receive or send Sms. ADDRESS, // 2 mobile phone number Sms. BODY, // 3 content Sms. DATE, // 4 DATE Sms. PROTOCOL // 5 PROTOCOL}; public static final int COLUMN_INDEX_ID = 0; public static final int COLUMN_INDEX_TYPE = 1; public static final int COLUMN_INDEX_PHONE = 2; public static final int COLUMN_INDEX_BODY = 3; public static final int COLUMN_INDEX_DATE = 4; public static final int COLUMN_INDEX_PROTOCOL = 5; public GetSMSInfo (Context context) {this. infos = new ArrayList
  
   
(); This. mResolver = context. getContentResolver (); this. context = context;}/*** get SMS information */public List
   
    
GetSmsInfo () {// get the last IDlong last_sms_id = UPSharedPreferences of the last retrieval. getLong (context, "card", "last_sms_id", 0); Cursor cursor = Sms. query (mResolver, PROJECTION, "_ id>" + last_sms_id, "_ id"); int protocol; String body, date; if (cursor! = Null) {while (cursor. moveToNext () {last_sms_id = cursor. getLong (COLUMN_INDEX_ID); body = cursor. getString (COLUMN_INDEX_BODY); date = cursor. getString (COLUMN_INDEX_DATE); protocol = cursor. getInt (COLUMN_INDEX_PROTOCOL); if (protocol = 0) {// receiving information SMSInfo info = new SMSInfo (); info. setId (last_sms_id); info. setSmsBody (body); info. setSmsDateTime (date); infos. add (info) ;}} cursor. close () ;}// Save the latest IDUPSharedPreferences. setLong (context, "card", "last_sms_id", last_sms_id); return infos ;}}
   
  
 
Read and retrieve all qualified text messages. And then we finally parse the conditions one by one. This involves some private information and will not show the effect.

Zookeeper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.