• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007-2008 Esmertec AG.
3  * Copyright (C) 2007-2008 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package com.android.mms.transaction;
19 
20 import static android.content.Intent.ACTION_BOOT_COMPLETED;
21 import static android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION;
22 
23 import java.util.Calendar;
24 import java.util.GregorianCalendar;
25 
26 import com.android.mms.data.Contact;
27 import com.android.mms.data.Conversation;
28 import com.android.mms.ui.ClassZeroActivity;
29 import com.android.mms.util.Recycler;
30 import com.android.mms.util.SendingProgressTokenManager;
31 import com.android.mms.widget.MmsWidgetProvider;
32 import com.google.android.mms.MmsException;
33 import android.database.sqlite.SqliteWrapper;
34 
35 import android.app.Activity;
36 import android.app.Service;
37 import android.content.ContentResolver;
38 import android.content.ContentUris;
39 import android.content.ContentValues;
40 import android.content.Context;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.database.Cursor;
44 import android.net.Uri;
45 import android.os.Handler;
46 import android.os.HandlerThread;
47 import android.os.IBinder;
48 import android.os.Looper;
49 import android.os.Message;
50 import android.os.Process;
51 import android.provider.Telephony.Sms;
52 import android.provider.Telephony.Threads;
53 import android.provider.Telephony.Sms.Inbox;
54 import android.provider.Telephony.Sms.Intents;
55 import android.provider.Telephony.Sms.Outbox;
56 import android.telephony.ServiceState;
57 import android.telephony.SmsManager;
58 import android.telephony.SmsMessage;
59 import android.text.TextUtils;
60 import android.util.Log;
61 import android.widget.Toast;
62 
63 import com.android.internal.telephony.TelephonyIntents;
64 import com.android.mms.R;
65 import com.android.mms.LogTag;
66 
67 /**
68  * This service essentially plays the role of a "worker thread", allowing us to store
69  * incoming messages to the database, update notifications, etc. without blocking the
70  * main thread that SmsReceiver runs on.
71  */
72 public class SmsReceiverService extends Service {
73     private static final String TAG = "SmsReceiverService";
74 
75     private ServiceHandler mServiceHandler;
76     private Looper mServiceLooper;
77     private boolean mSending;
78 
79     public static final String MESSAGE_SENT_ACTION =
80         "com.android.mms.transaction.MESSAGE_SENT";
81 
82     // Indicates next message can be picked up and sent out.
83     public static final String EXTRA_MESSAGE_SENT_SEND_NEXT ="SendNextMsg";
84 
85     public static final String ACTION_SEND_MESSAGE =
86         "com.android.mms.transaction.SEND_MESSAGE";
87 
88     // This must match the column IDs below.
89     private static final String[] SEND_PROJECTION = new String[] {
90         Sms._ID,        //0
91         Sms.THREAD_ID,  //1
92         Sms.ADDRESS,    //2
93         Sms.BODY,       //3
94         Sms.STATUS,     //4
95 
96     };
97 
98     public Handler mToastHandler = new Handler();
99 
100     // This must match SEND_PROJECTION.
101     private static final int SEND_COLUMN_ID         = 0;
102     private static final int SEND_COLUMN_THREAD_ID  = 1;
103     private static final int SEND_COLUMN_ADDRESS    = 2;
104     private static final int SEND_COLUMN_BODY       = 3;
105     private static final int SEND_COLUMN_STATUS     = 4;
106 
107     private int mResultCode;
108 
109     @Override
onCreate()110     public void onCreate() {
111         // Temporarily removed for this duplicate message track down.
112 //        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
113 //            Log.v(TAG, "onCreate");
114 //        }
115 
116         // Start up the thread running the service.  Note that we create a
117         // separate thread because the service normally runs in the process's
118         // main thread, which we don't want to block.
119         HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
120         thread.start();
121 
122         mServiceLooper = thread.getLooper();
123         mServiceHandler = new ServiceHandler(mServiceLooper);
124     }
125 
126     @Override
onStartCommand(Intent intent, int flags, int startId)127     public int onStartCommand(Intent intent, int flags, int startId) {
128         // Temporarily removed for this duplicate message track down.
129 
130         mResultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
131 
132         if (mResultCode != 0) {
133             Log.v(TAG, "onStart: #" + startId + " mResultCode: " + mResultCode +
134                     " = " + translateResultCode(mResultCode));
135         }
136 
137         Message msg = mServiceHandler.obtainMessage();
138         msg.arg1 = startId;
139         msg.obj = intent;
140         mServiceHandler.sendMessage(msg);
141         return Service.START_NOT_STICKY;
142     }
143 
translateResultCode(int resultCode)144     private static String translateResultCode(int resultCode) {
145         switch (resultCode) {
146             case Activity.RESULT_OK:
147                 return "Activity.RESULT_OK";
148             case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
149                 return "SmsManager.RESULT_ERROR_GENERIC_FAILURE";
150             case SmsManager.RESULT_ERROR_RADIO_OFF:
151                 return "SmsManager.RESULT_ERROR_RADIO_OFF";
152             case SmsManager.RESULT_ERROR_NULL_PDU:
153                 return "SmsManager.RESULT_ERROR_NULL_PDU";
154             case SmsManager.RESULT_ERROR_NO_SERVICE:
155                 return "SmsManager.RESULT_ERROR_NO_SERVICE";
156             case SmsManager.RESULT_ERROR_LIMIT_EXCEEDED:
157                 return "SmsManager.RESULT_ERROR_LIMIT_EXCEEDED";
158             case SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE:
159                 return "SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE";
160             default:
161                 return "Unknown error code";
162         }
163     }
164 
165     @Override
onDestroy()166     public void onDestroy() {
167         // Temporarily removed for this duplicate message track down.
168 //        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
169 //            Log.v(TAG, "onDestroy");
170 //        }
171         mServiceLooper.quit();
172     }
173 
174     @Override
onBind(Intent intent)175     public IBinder onBind(Intent intent) {
176         return null;
177     }
178 
179     private final class ServiceHandler extends Handler {
ServiceHandler(Looper looper)180         public ServiceHandler(Looper looper) {
181             super(looper);
182         }
183 
184         /**
185          * Handle incoming transaction requests.
186          * The incoming requests are initiated by the MMSC Server or by the MMS Client itself.
187          */
188         @Override
handleMessage(Message msg)189         public void handleMessage(Message msg) {
190             int serviceId = msg.arg1;
191             Intent intent = (Intent)msg.obj;
192             if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
193                 Log.v(TAG, "handleMessage serviceId: " + serviceId + " intent: " + intent);
194             }
195             if (intent != null) {
196                 String action = intent.getAction();
197 
198                 int error = intent.getIntExtra("errorCode", 0);
199 
200                 if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
201                     Log.v(TAG, "handleMessage action: " + action + " error: " + error);
202                 }
203 
204                 if (MESSAGE_SENT_ACTION.equals(intent.getAction())) {
205                     handleSmsSent(intent, error);
206                 } else if (SMS_RECEIVED_ACTION.equals(action)) {
207                     handleSmsReceived(intent, error);
208                 } else if (ACTION_BOOT_COMPLETED.equals(action)) {
209                     handleBootCompleted();
210                 } else if (TelephonyIntents.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
211                     handleServiceStateChanged(intent);
212                 } else if (ACTION_SEND_MESSAGE.endsWith(action)) {
213                     handleSendMessage();
214                 }
215             }
216             // NOTE: We MUST not call stopSelf() directly, since we need to
217             // make sure the wake lock acquired by AlertReceiver is released.
218             SmsReceiver.finishStartingService(SmsReceiverService.this, serviceId);
219         }
220     }
221 
handleServiceStateChanged(Intent intent)222     private void handleServiceStateChanged(Intent intent) {
223         // If service just returned, start sending out the queued messages
224         ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras());
225         if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
226             sendFirstQueuedMessage();
227         }
228     }
229 
handleSendMessage()230     private void handleSendMessage() {
231         if (!mSending) {
232             sendFirstQueuedMessage();
233         }
234     }
235 
sendFirstQueuedMessage()236     public synchronized void sendFirstQueuedMessage() {
237         boolean success = true;
238         // get all the queued messages from the database
239         final Uri uri = Uri.parse("content://sms/queued");
240         ContentResolver resolver = getContentResolver();
241         Cursor c = SqliteWrapper.query(this, resolver, uri,
242                         SEND_PROJECTION, null, null, "date ASC");   // date ASC so we send out in
243                                                                     // same order the user tried
244                                                                     // to send messages.
245         if (c != null) {
246             try {
247                 if (c.moveToFirst()) {
248                     String msgText = c.getString(SEND_COLUMN_BODY);
249                     String address = c.getString(SEND_COLUMN_ADDRESS);
250                     int threadId = c.getInt(SEND_COLUMN_THREAD_ID);
251                     int status = c.getInt(SEND_COLUMN_STATUS);
252 
253                     int msgId = c.getInt(SEND_COLUMN_ID);
254                     Uri msgUri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgId);
255 
256                     SmsMessageSender sender = new SmsSingleRecipientSender(this,
257                             address, msgText, threadId, status == Sms.STATUS_PENDING,
258                             msgUri);
259 
260                     if (LogTag.DEBUG_SEND ||
261                             LogTag.VERBOSE ||
262                             Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
263                         Log.v(TAG, "sendFirstQueuedMessage " + msgUri +
264                                 ", address: " + address +
265                                 ", threadId: " + threadId);
266                     }
267 
268                     try {
269                         sender.sendMessage(SendingProgressTokenManager.NO_TOKEN);;
270                         mSending = true;
271                     } catch (MmsException e) {
272                         Log.e(TAG, "sendFirstQueuedMessage: failed to send message " + msgUri
273                                 + ", caught ", e);
274                         mSending = false;
275                         messageFailedToSend(msgUri, SmsManager.RESULT_ERROR_GENERIC_FAILURE);
276                         success = false;
277                     }
278                 }
279             } finally {
280                 c.close();
281             }
282         }
283         if (success) {
284             // We successfully sent all the messages in the queue. We don't need to
285             // be notified of any service changes any longer.
286             unRegisterForServiceStateChanges();
287         }
288     }
289 
handleSmsSent(Intent intent, int error)290     private void handleSmsSent(Intent intent, int error) {
291         Uri uri = intent.getData();
292         mSending = false;
293         boolean sendNextMsg = intent.getBooleanExtra(EXTRA_MESSAGE_SENT_SEND_NEXT, false);
294 
295         if (LogTag.DEBUG_SEND) {
296             Log.v(TAG, "handleSmsSent uri: " + uri + " sendNextMsg: " + sendNextMsg +
297                     " mResultCode: " + mResultCode +
298                     " = " + translateResultCode(mResultCode) + " error: " + error);
299         }
300 
301         if (mResultCode == Activity.RESULT_OK) {
302             if (LogTag.DEBUG_SEND || Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
303                 Log.v(TAG, "handleSmsSent move message to sent folder uri: " + uri);
304             }
305             if (!Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_SENT, error)) {
306                 Log.e(TAG, "handleSmsSent: failed to move message " + uri + " to sent folder");
307             }
308             if (sendNextMsg) {
309                 sendFirstQueuedMessage();
310             }
311 
312             // Update the notification for failed messages since they may be deleted.
313             MessagingNotification.nonBlockingUpdateSendFailedNotification(this);
314         } else if ((mResultCode == SmsManager.RESULT_ERROR_RADIO_OFF) ||
315                 (mResultCode == SmsManager.RESULT_ERROR_NO_SERVICE)) {
316             if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
317                 Log.v(TAG, "handleSmsSent: no service, queuing message w/ uri: " + uri);
318             }
319             // We got an error with no service or no radio. Register for state changes so
320             // when the status of the connection/radio changes, we can try to send the
321             // queued up messages.
322             registerForServiceStateChanges();
323             // We couldn't send the message, put in the queue to retry later.
324             Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_QUEUED, error);
325             mToastHandler.post(new Runnable() {
326                 public void run() {
327                     Toast.makeText(SmsReceiverService.this, getString(R.string.message_queued),
328                             Toast.LENGTH_SHORT).show();
329                 }
330             });
331         } else if (mResultCode == SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE) {
332             mToastHandler.post(new Runnable() {
333                 public void run() {
334                     Toast.makeText(SmsReceiverService.this, getString(R.string.fdn_check_failure),
335                             Toast.LENGTH_SHORT).show();
336                 }
337             });
338         } else {
339             messageFailedToSend(uri, error);
340             if (sendNextMsg) {
341                 sendFirstQueuedMessage();
342             }
343         }
344     }
345 
messageFailedToSend(Uri uri, int error)346     private void messageFailedToSend(Uri uri, int error) {
347         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
348             Log.v(TAG, "messageFailedToSend msg failed uri: " + uri + " error: " + error);
349         }
350         Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_FAILED, error);
351         MessagingNotification.notifySendFailed(getApplicationContext(), true);
352     }
353 
handleSmsReceived(Intent intent, int error)354     private void handleSmsReceived(Intent intent, int error) {
355         SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
356         String format = intent.getStringExtra("format");
357         Uri messageUri = insertMessage(this, msgs, error, format);
358 
359         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
360             SmsMessage sms = msgs[0];
361             Log.v(TAG, "handleSmsReceived" + (sms.isReplace() ? "(replace)" : "") +
362                     " messageUri: " + messageUri +
363                     ", address: " + sms.getOriginatingAddress() +
364                     ", body: " + sms.getMessageBody());
365         }
366 
367         if (messageUri != null) {
368             long threadId = MessagingNotification.getSmsThreadId(this, messageUri);
369             // Called off of the UI thread so ok to block.
370             MessagingNotification.blockingUpdateNewMessageIndicator(this, threadId, false);
371         }
372     }
373 
handleBootCompleted()374     private void handleBootCompleted() {
375         // Some messages may get stuck in the outbox. At this point, they're probably irrelevant
376         // to the user, so mark them as failed and notify the user, who can then decide whether to
377         // resend them manually.
378         int numMoved = moveOutboxMessagesToFailedBox();
379         if (numMoved > 0) {
380             MessagingNotification.notifySendFailed(getApplicationContext(), true);
381         }
382 
383         // Send any queued messages that were waiting from before the reboot.
384         sendFirstQueuedMessage();
385 
386         // Called off of the UI thread so ok to block.
387         MessagingNotification.blockingUpdateNewMessageIndicator(
388                 this, MessagingNotification.THREAD_ALL, false);
389     }
390 
391     /**
392      * Move all messages that are in the outbox to the failed state and set them to unread.
393      * @return The number of messages that were actually moved
394      */
moveOutboxMessagesToFailedBox()395     private int moveOutboxMessagesToFailedBox() {
396         ContentValues values = new ContentValues(3);
397 
398         values.put(Sms.TYPE, Sms.MESSAGE_TYPE_FAILED);
399         values.put(Sms.ERROR_CODE, SmsManager.RESULT_ERROR_GENERIC_FAILURE);
400         values.put(Sms.READ, Integer.valueOf(0));
401 
402         int messageCount = SqliteWrapper.update(
403                 getApplicationContext(), getContentResolver(), Outbox.CONTENT_URI,
404                 values, "type = " + Sms.MESSAGE_TYPE_OUTBOX, null);
405         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
406             Log.v(TAG, "moveOutboxMessagesToFailedBox messageCount: " + messageCount);
407         }
408         return messageCount;
409     }
410 
411     public static final String CLASS_ZERO_BODY_KEY = "CLASS_ZERO_BODY";
412 
413     // This must match the column IDs below.
414     private final static String[] REPLACE_PROJECTION = new String[] {
415         Sms._ID,
416         Sms.ADDRESS,
417         Sms.PROTOCOL
418     };
419 
420     // This must match REPLACE_PROJECTION.
421     private static final int REPLACE_COLUMN_ID = 0;
422 
423     /**
424      * If the message is a class-zero message, display it immediately
425      * and return null.  Otherwise, store it using the
426      * <code>ContentResolver</code> and return the
427      * <code>Uri</code> of the thread containing this message
428      * so that we can use it for notification.
429      */
insertMessage(Context context, SmsMessage[] msgs, int error, String format)430     private Uri insertMessage(Context context, SmsMessage[] msgs, int error, String format) {
431         // Build the helper classes to parse the messages.
432         SmsMessage sms = msgs[0];
433 
434         if (sms.getMessageClass() == SmsMessage.MessageClass.CLASS_0) {
435             displayClassZeroMessage(context, sms, format);
436             return null;
437         } else if (sms.isReplace()) {
438             return replaceMessage(context, msgs, error);
439         } else {
440             return storeMessage(context, msgs, error);
441         }
442     }
443 
444     /**
445      * This method is used if this is a "replace short message" SMS.
446      * We find any existing message that matches the incoming
447      * message's originating address and protocol identifier.  If
448      * there is one, we replace its fields with those of the new
449      * message.  Otherwise, we store the new message as usual.
450      *
451      * See TS 23.040 9.2.3.9.
452      */
replaceMessage(Context context, SmsMessage[] msgs, int error)453     private Uri replaceMessage(Context context, SmsMessage[] msgs, int error) {
454         SmsMessage sms = msgs[0];
455         ContentValues values = extractContentValues(sms);
456         values.put(Sms.ERROR_CODE, error);
457         int pduCount = msgs.length;
458 
459         if (pduCount == 1) {
460             // There is only one part, so grab the body directly.
461             values.put(Inbox.BODY, replaceFormFeeds(sms.getDisplayMessageBody()));
462         } else {
463             // Build up the body from the parts.
464             StringBuilder body = new StringBuilder();
465             for (int i = 0; i < pduCount; i++) {
466                 sms = msgs[i];
467                 if (sms.mWrappedSmsMessage != null) {
468                     body.append(sms.getDisplayMessageBody());
469                 }
470             }
471             values.put(Inbox.BODY, replaceFormFeeds(body.toString()));
472         }
473 
474         ContentResolver resolver = context.getContentResolver();
475         String originatingAddress = sms.getOriginatingAddress();
476         int protocolIdentifier = sms.getProtocolIdentifier();
477         String selection =
478                 Sms.ADDRESS + " = ? AND " +
479                 Sms.PROTOCOL + " = ?";
480         String[] selectionArgs = new String[] {
481             originatingAddress, Integer.toString(protocolIdentifier)
482         };
483 
484         Cursor cursor = SqliteWrapper.query(context, resolver, Inbox.CONTENT_URI,
485                             REPLACE_PROJECTION, selection, selectionArgs, null);
486 
487         if (cursor != null) {
488             try {
489                 if (cursor.moveToFirst()) {
490                     long messageId = cursor.getLong(REPLACE_COLUMN_ID);
491                     Uri messageUri = ContentUris.withAppendedId(
492                             Sms.CONTENT_URI, messageId);
493 
494                     SqliteWrapper.update(context, resolver, messageUri,
495                                         values, null, null);
496                     return messageUri;
497                 }
498             } finally {
499                 cursor.close();
500             }
501         }
502         return storeMessage(context, msgs, error);
503     }
504 
replaceFormFeeds(String s)505     public static String replaceFormFeeds(String s) {
506         // Some providers send formfeeds in their messages. Convert those formfeeds to newlines.
507         return s.replace('\f', '\n');
508     }
509 
510 //    private static int count = 0;
511 
storeMessage(Context context, SmsMessage[] msgs, int error)512     private Uri storeMessage(Context context, SmsMessage[] msgs, int error) {
513         SmsMessage sms = msgs[0];
514 
515         // Store the message in the content provider.
516         ContentValues values = extractContentValues(sms);
517         values.put(Sms.ERROR_CODE, error);
518         int pduCount = msgs.length;
519 
520         if (pduCount == 1) {
521             // There is only one part, so grab the body directly.
522             values.put(Inbox.BODY, replaceFormFeeds(sms.getDisplayMessageBody()));
523         } else {
524             // Build up the body from the parts.
525             StringBuilder body = new StringBuilder();
526             for (int i = 0; i < pduCount; i++) {
527                 sms = msgs[i];
528                 if (sms.mWrappedSmsMessage != null) {
529                     body.append(sms.getDisplayMessageBody());
530                 }
531             }
532             values.put(Inbox.BODY, replaceFormFeeds(body.toString()));
533         }
534 
535         // Make sure we've got a thread id so after the insert we'll be able to delete
536         // excess messages.
537         Long threadId = values.getAsLong(Sms.THREAD_ID);
538         String address = values.getAsString(Sms.ADDRESS);
539 
540         // Code for debugging and easy injection of short codes, non email addresses, etc.
541         // See Contact.isAlphaNumber() for further comments and results.
542 //        switch (count++ % 8) {
543 //            case 0: address = "AB12"; break;
544 //            case 1: address = "12"; break;
545 //            case 2: address = "Jello123"; break;
546 //            case 3: address = "T-Mobile"; break;
547 //            case 4: address = "Mobile1"; break;
548 //            case 5: address = "Dogs77"; break;
549 //            case 6: address = "****1"; break;
550 //            case 7: address = "#4#5#6#"; break;
551 //        }
552 
553         if (!TextUtils.isEmpty(address)) {
554             Contact cacheContact = Contact.get(address,true);
555             if (cacheContact != null) {
556                 address = cacheContact.getNumber();
557             }
558         } else {
559             address = getString(R.string.unknown_sender);
560             values.put(Sms.ADDRESS, address);
561         }
562 
563         if (((threadId == null) || (threadId == 0)) && (address != null)) {
564             threadId = Conversation.getOrCreateThreadId(context, address);
565             values.put(Sms.THREAD_ID, threadId);
566         }
567 
568         ContentResolver resolver = context.getContentResolver();
569 
570         Uri insertedUri = SqliteWrapper.insert(context, resolver, Inbox.CONTENT_URI, values);
571 
572         // Now make sure we're not over the limit in stored messages
573         Recycler.getSmsRecycler().deleteOldMessagesByThreadId(context, threadId);
574         MmsWidgetProvider.notifyDatasetChanged(context);
575 
576         return insertedUri;
577     }
578 
579     /**
580      * Extract all the content values except the body from an SMS
581      * message.
582      */
extractContentValues(SmsMessage sms)583     private ContentValues extractContentValues(SmsMessage sms) {
584         // Store the message in the content provider.
585         ContentValues values = new ContentValues();
586 
587         values.put(Inbox.ADDRESS, sms.getDisplayOriginatingAddress());
588 
589         // Use now for the timestamp to avoid confusion with clock
590         // drift between the handset and the SMSC.
591         // Check to make sure the system is giving us a non-bogus time.
592         Calendar buildDate = new GregorianCalendar(2011, 8, 18);    // 18 Sep 2011
593         Calendar nowDate = new GregorianCalendar();
594         long now = System.currentTimeMillis();
595         nowDate.setTimeInMillis(now);
596 
597         if (nowDate.before(buildDate)) {
598             // It looks like our system clock isn't set yet because the current time right now
599             // is before an arbitrary time we made this build. Instead of inserting a bogus
600             // receive time in this case, use the timestamp of when the message was sent.
601             now = sms.getTimestampMillis();
602         }
603 
604         values.put(Inbox.DATE, new Long(now));
605         values.put(Inbox.DATE_SENT, Long.valueOf(sms.getTimestampMillis()));
606         values.put(Inbox.PROTOCOL, sms.getProtocolIdentifier());
607         values.put(Inbox.READ, 0);
608         values.put(Inbox.SEEN, 0);
609         if (sms.getPseudoSubject().length() > 0) {
610             values.put(Inbox.SUBJECT, sms.getPseudoSubject());
611         }
612         values.put(Inbox.REPLY_PATH_PRESENT, sms.isReplyPathPresent() ? 1 : 0);
613         values.put(Inbox.SERVICE_CENTER, sms.getServiceCenterAddress());
614         return values;
615     }
616 
617     /**
618      * Displays a class-zero message immediately in a pop-up window
619      * with the number from where it received the Notification with
620      * the body of the message
621      *
622      */
displayClassZeroMessage(Context context, SmsMessage sms, String format)623     private void displayClassZeroMessage(Context context, SmsMessage sms, String format) {
624         // Using NEW_TASK here is necessary because we're calling
625         // startActivity from outside an activity.
626         Intent smsDialogIntent = new Intent(context, ClassZeroActivity.class)
627                 .putExtra("pdu", sms.getPdu())
628                 .putExtra("format", format)
629                 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
630                           | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
631 
632         context.startActivity(smsDialogIntent);
633     }
634 
registerForServiceStateChanges()635     private void registerForServiceStateChanges() {
636         Context context = getApplicationContext();
637         unRegisterForServiceStateChanges();
638 
639         IntentFilter intentFilter = new IntentFilter();
640         intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
641         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
642             Log.v(TAG, "registerForServiceStateChanges");
643         }
644 
645         context.registerReceiver(SmsReceiver.getInstance(), intentFilter);
646     }
647 
unRegisterForServiceStateChanges()648     private void unRegisterForServiceStateChanges() {
649         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
650             Log.v(TAG, "unRegisterForServiceStateChanges");
651         }
652         try {
653             Context context = getApplicationContext();
654             context.unregisterReceiver(SmsReceiver.getInstance());
655         } catch (IllegalArgumentException e) {
656             // Allow un-matched register-unregister calls
657         }
658     }
659 }
660 
661 
662