SmsReceiverService.java revision bd2a8f5bd39ce46a43b5bcc759432ebea4f68369
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
18package com.android.mms.transaction;
19
20import static android.content.Intent.ACTION_BOOT_COMPLETED;
21import static android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION;
22
23import com.android.mms.data.Contact;
24import com.android.mms.ui.ClassZeroActivity;
25import com.android.mms.util.Recycler;
26import com.android.mms.util.SendingProgressTokenManager;
27import com.google.android.mms.MmsException;
28import android.database.sqlite.SqliteWrapper;
29
30import android.app.Activity;
31import android.app.Service;
32import android.content.ContentResolver;
33import android.content.ContentUris;
34import android.content.ContentValues;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.database.Cursor;
39import android.net.Uri;
40import android.os.Handler;
41import android.os.HandlerThread;
42import android.os.IBinder;
43import android.os.Looper;
44import android.os.Message;
45import android.os.Process;
46import android.provider.Telephony.Sms;
47import android.provider.Telephony.Threads;
48import android.provider.Telephony.Sms.Inbox;
49import android.provider.Telephony.Sms.Intents;
50import android.provider.Telephony.Sms.Outbox;
51import android.provider.Telephony;
52import android.telephony.ServiceState;
53import android.telephony.SmsManager;
54import android.telephony.SmsMessage;
55import android.text.TextUtils;
56import android.util.Log;
57import android.widget.Toast;
58
59import com.android.internal.telephony.TelephonyIntents;
60import com.android.mms.R;
61import com.android.mms.LogTag;
62
63/**
64 * This service essentially plays the role of a "worker thread", allowing us to store
65 * incoming messages to the database, update notifications, etc. without blocking the
66 * main thread that SmsReceiver runs on.
67 */
68public class SmsReceiverService extends Service {
69    private static final String TAG = "SmsReceiverService";
70
71    private ServiceHandler mServiceHandler;
72    private Looper mServiceLooper;
73    private boolean mSending;
74
75    public static final String MESSAGE_SENT_ACTION =
76        "com.android.mms.transaction.MESSAGE_SENT";
77
78    // Indicates next message can be picked up and sent out.
79    public static final String EXTRA_MESSAGE_SENT_SEND_NEXT ="SendNextMsg";
80
81    public static final String ACTION_SEND_MESSAGE =
82        "com.android.mms.transaction.SEND_MESSAGE";
83
84    // This must match the column IDs below.
85    private static final String[] SEND_PROJECTION = new String[] {
86        Sms._ID,        //0
87        Sms.THREAD_ID,  //1
88        Sms.ADDRESS,    //2
89        Sms.BODY,       //3
90        Sms.STATUS,     //4
91
92    };
93
94    public Handler mToastHandler = new Handler();
95
96    // This must match SEND_PROJECTION.
97    private static final int SEND_COLUMN_ID         = 0;
98    private static final int SEND_COLUMN_THREAD_ID  = 1;
99    private static final int SEND_COLUMN_ADDRESS    = 2;
100    private static final int SEND_COLUMN_BODY       = 3;
101    private static final int SEND_COLUMN_STATUS     = 4;
102
103    private int mResultCode;
104
105    @Override
106    public void onCreate() {
107        // Temporarily removed for this duplicate message track down.
108//        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
109//            Log.v(TAG, "onCreate");
110//        }
111
112        // Start up the thread running the service.  Note that we create a
113        // separate thread because the service normally runs in the process's
114        // main thread, which we don't want to block.
115        HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
116        thread.start();
117
118        mServiceLooper = thread.getLooper();
119        mServiceHandler = new ServiceHandler(mServiceLooper);
120    }
121
122    @Override
123    public int onStartCommand(Intent intent, int flags, int startId) {
124        // Temporarily removed for this duplicate message track down.
125//        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
126//            Log.v(TAG, "onStart: #" + startId + ": " + intent.getExtras());
127//        }
128
129        mResultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
130
131        Message msg = mServiceHandler.obtainMessage();
132        msg.arg1 = startId;
133        msg.obj = intent;
134        mServiceHandler.sendMessage(msg);
135        return Service.START_NOT_STICKY;
136    }
137
138    @Override
139    public void onDestroy() {
140        // Temporarily removed for this duplicate message track down.
141//        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
142//            Log.v(TAG, "onDestroy");
143//        }
144        mServiceLooper.quit();
145    }
146
147    @Override
148    public IBinder onBind(Intent intent) {
149        return null;
150    }
151
152    private final class ServiceHandler extends Handler {
153        public ServiceHandler(Looper looper) {
154            super(looper);
155        }
156
157        /**
158         * Handle incoming transaction requests.
159         * The incoming requests are initiated by the MMSC Server or by the MMS Client itself.
160         */
161        @Override
162        public void handleMessage(Message msg) {
163            int serviceId = msg.arg1;
164            Intent intent = (Intent)msg.obj;
165            if (intent != null) {
166                String action = intent.getAction();
167
168                int error = intent.getIntExtra("errorCode", 0);
169
170                if (MESSAGE_SENT_ACTION.equals(intent.getAction())) {
171                    handleSmsSent(intent, error);
172                } else if (SMS_RECEIVED_ACTION.equals(action)) {
173                    handleSmsReceived(intent, error);
174                } else if (ACTION_BOOT_COMPLETED.equals(action)) {
175                    handleBootCompleted();
176                } else if (TelephonyIntents.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
177                    handleServiceStateChanged(intent);
178                } else if (ACTION_SEND_MESSAGE.endsWith(action)) {
179                    handleSendMessage();
180                }
181            }
182            // NOTE: We MUST not call stopSelf() directly, since we need to
183            // make sure the wake lock acquired by AlertReceiver is released.
184            SmsReceiver.finishStartingService(SmsReceiverService.this, serviceId);
185        }
186    }
187
188    private void handleServiceStateChanged(Intent intent) {
189        // If service just returned, start sending out the queued messages
190        ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras());
191        if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
192            sendFirstQueuedMessage();
193        }
194    }
195
196    private void handleSendMessage() {
197        if (!mSending) {
198            sendFirstQueuedMessage();
199        }
200    }
201
202    public synchronized void sendFirstQueuedMessage() {
203        boolean success = true;
204        // get all the queued messages from the database
205        final Uri uri = Uri.parse("content://sms/queued");
206        ContentResolver resolver = getContentResolver();
207        Cursor c = SqliteWrapper.query(this, resolver, uri,
208                        SEND_PROJECTION, null, null, "date ASC");   // date ASC so we send out in
209                                                                    // same order the user tried
210                                                                    // to send messages.
211        if (c != null) {
212            try {
213                if (c.moveToFirst()) {
214                    String msgText = c.getString(SEND_COLUMN_BODY);
215                    String address = c.getString(SEND_COLUMN_ADDRESS);
216                    int threadId = c.getInt(SEND_COLUMN_THREAD_ID);
217                    int status = c.getInt(SEND_COLUMN_STATUS);
218
219                    int msgId = c.getInt(SEND_COLUMN_ID);
220                    Uri msgUri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgId);
221
222                    SmsMessageSender sender = new SmsSingleRecipientSender(this,
223                            address, msgText, threadId, status == Sms.STATUS_PENDING,
224                            msgUri);
225
226                    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
227                        Log.v(TAG, "sendFirstQueuedMessage " + msgUri +
228                                ", address: " + address +
229                                ", threadId: " + threadId +
230                                ", body: " + msgText);
231                    }
232                    try {
233                        sender.sendMessage(SendingProgressTokenManager.NO_TOKEN);;
234                        mSending = true;
235                    } catch (MmsException e) {
236                        Log.e(TAG, "sendFirstQueuedMessage: failed to send message " + msgUri
237                                + ", caught ", e);
238                        success = false;
239                    }
240                }
241            } finally {
242                c.close();
243            }
244        }
245        if (success) {
246            // We successfully sent all the messages in the queue. We don't need to
247            // be notified of any service changes any longer.
248            unRegisterForServiceStateChanges();
249        }
250    }
251
252    private void handleSmsSent(Intent intent, int error) {
253        Uri uri = intent.getData();
254        mSending = false;
255        boolean sendNextMsg = intent.getBooleanExtra(EXTRA_MESSAGE_SENT_SEND_NEXT, false);
256
257        if (mResultCode == Activity.RESULT_OK) {
258            if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
259                Log.v(TAG, "handleSmsSent sending uri: " + uri);
260            }
261            if (!Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_SENT, error)) {
262                Log.e(TAG, "handleSmsSent: failed to move message " + uri + " to sent folder");
263            }
264            if (sendNextMsg) {
265                sendFirstQueuedMessage();
266            }
267
268            // Update the notification for failed messages since they may be deleted.
269            MessagingNotification.updateSendFailedNotification(this);
270        } else if ((mResultCode == SmsManager.RESULT_ERROR_RADIO_OFF) ||
271                (mResultCode == SmsManager.RESULT_ERROR_NO_SERVICE)) {
272            if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
273                Log.v(TAG, "handleSmsSent: no service, queuing message w/ uri: " + uri);
274            }
275            // We got an error with no service or no radio. Register for state changes so
276            // when the status of the connection/radio changes, we can try to send the
277            // queued up messages.
278            registerForServiceStateChanges();
279            // We couldn't send the message, put in the queue to retry later.
280            Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_QUEUED, error);
281            mToastHandler.post(new Runnable() {
282                public void run() {
283                    Toast.makeText(SmsReceiverService.this, getString(R.string.message_queued),
284                            Toast.LENGTH_SHORT).show();
285                }
286            });
287        } else {
288            if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
289                Log.v(TAG, "handleSmsSent msg failed uri: " + uri);
290            }
291            Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_FAILED, error);
292            MessagingNotification.notifySendFailed(getApplicationContext(), true);
293            if (sendNextMsg) {
294                sendFirstQueuedMessage();
295            }
296        }
297    }
298
299    private void handleSmsReceived(Intent intent, int error) {
300        SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
301        Uri messageUri = insertMessage(this, msgs, error);
302
303        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
304            SmsMessage sms = msgs[0];
305            Log.v(TAG, "handleSmsReceived" + (sms.isReplace() ? "(replace)" : "") +
306                    " messageUri: " + messageUri +
307                    ", address: " + sms.getOriginatingAddress() +
308                    ", body: " + sms.getMessageBody());
309        }
310
311        if (messageUri != null) {
312            // Called off of the UI thread so ok to block.
313            MessagingNotification.blockingUpdateNewMessageIndicator(this, true, false);
314        }
315    }
316
317    private void handleBootCompleted() {
318        moveOutboxMessagesToQueuedBox();
319        sendFirstQueuedMessage();
320
321        // Called off of the UI thread so ok to block.
322        MessagingNotification.blockingUpdateNewMessageIndicator(this, true, false);
323    }
324
325    private void moveOutboxMessagesToQueuedBox() {
326        ContentValues values = new ContentValues(1);
327
328        values.put(Sms.TYPE, Sms.MESSAGE_TYPE_QUEUED);
329
330        SqliteWrapper.update(
331                getApplicationContext(), getContentResolver(), Outbox.CONTENT_URI,
332                values, "type = " + Sms.MESSAGE_TYPE_OUTBOX, null);
333    }
334
335    public static final String CLASS_ZERO_BODY_KEY = "CLASS_ZERO_BODY";
336
337    // This must match the column IDs below.
338    private final static String[] REPLACE_PROJECTION = new String[] {
339        Sms._ID,
340        Sms.ADDRESS,
341        Sms.PROTOCOL
342    };
343
344    // This must match REPLACE_PROJECTION.
345    private static final int REPLACE_COLUMN_ID = 0;
346
347    /**
348     * If the message is a class-zero message, display it immediately
349     * and return null.  Otherwise, store it using the
350     * <code>ContentResolver</code> and return the
351     * <code>Uri</code> of the thread containing this message
352     * so that we can use it for notification.
353     */
354    private Uri insertMessage(Context context, SmsMessage[] msgs, int error) {
355        // Build the helper classes to parse the messages.
356        SmsMessage sms = msgs[0];
357
358        if (sms.getMessageClass() == SmsMessage.MessageClass.CLASS_0) {
359            displayClassZeroMessage(context, sms);
360            return null;
361        } else if (sms.isReplace()) {
362            return replaceMessage(context, msgs, error);
363        } else {
364            return storeMessage(context, msgs, error);
365        }
366    }
367
368    /**
369     * This method is used if this is a "replace short message" SMS.
370     * We find any existing message that matches the incoming
371     * message's originating address and protocol identifier.  If
372     * there is one, we replace its fields with those of the new
373     * message.  Otherwise, we store the new message as usual.
374     *
375     * See TS 23.040 9.2.3.9.
376     */
377    private Uri replaceMessage(Context context, SmsMessage[] msgs, int error) {
378        SmsMessage sms = msgs[0];
379        ContentValues values = extractContentValues(sms);
380
381        values.put(Inbox.BODY, sms.getMessageBody());
382        values.put(Sms.ERROR_CODE, error);
383
384        ContentResolver resolver = context.getContentResolver();
385        String originatingAddress = sms.getOriginatingAddress();
386        int protocolIdentifier = sms.getProtocolIdentifier();
387        String selection =
388                Sms.ADDRESS + " = ? AND " +
389                Sms.PROTOCOL + " = ?";
390        String[] selectionArgs = new String[] {
391            originatingAddress, Integer.toString(protocolIdentifier)
392        };
393
394        Cursor cursor = SqliteWrapper.query(context, resolver, Inbox.CONTENT_URI,
395                            REPLACE_PROJECTION, selection, selectionArgs, null);
396
397        if (cursor != null) {
398            try {
399                if (cursor.moveToFirst()) {
400                    long messageId = cursor.getLong(REPLACE_COLUMN_ID);
401                    Uri messageUri = ContentUris.withAppendedId(
402                            Sms.CONTENT_URI, messageId);
403
404                    SqliteWrapper.update(context, resolver, messageUri,
405                                        values, null, null);
406                    return messageUri;
407                }
408            } finally {
409                cursor.close();
410            }
411        }
412        return storeMessage(context, msgs, error);
413    }
414
415    private Uri storeMessage(Context context, SmsMessage[] msgs, int error) {
416        SmsMessage sms = msgs[0];
417
418        // Store the message in the content provider.
419        ContentValues values = extractContentValues(sms);
420        values.put(Sms.ERROR_CODE, error);
421        int pduCount = msgs.length;
422
423        if (pduCount == 1) {
424            // There is only one part, so grab the body directly.
425            values.put(Inbox.BODY, sms.getDisplayMessageBody());
426        } else {
427            // Build up the body from the parts.
428            StringBuilder body = new StringBuilder();
429            for (int i = 0; i < pduCount; i++) {
430                sms = msgs[i];
431                body.append(sms.getDisplayMessageBody());
432            }
433            values.put(Inbox.BODY, body.toString());
434        }
435
436        // Make sure we've got a thread id so after the insert we'll be able to delete
437        // excess messages.
438        Long threadId = values.getAsLong(Sms.THREAD_ID);
439        String address = values.getAsString(Sms.ADDRESS);
440        if (!TextUtils.isEmpty(address)) {
441            Contact cacheContact = Contact.get(address,true);
442            if (cacheContact != null) {
443                address = cacheContact.getNumber();
444            }
445        } else {
446            address = getString(R.string.unknown_sender);
447            values.put(Sms.ADDRESS, address);
448        }
449
450        if (((threadId == null) || (threadId == 0)) && (address != null)) {
451            threadId = Threads.getOrCreateThreadId(context, address);
452            values.put(Sms.THREAD_ID, threadId);
453        }
454
455        ContentResolver resolver = context.getContentResolver();
456
457        Uri insertedUri = SqliteWrapper.insert(context, resolver, Inbox.CONTENT_URI, values);
458
459        // Now make sure we're not over the limit in stored messages
460        Recycler.getSmsRecycler().deleteOldMessagesByThreadId(getApplicationContext(), threadId);
461
462        return insertedUri;
463    }
464
465    /**
466     * Extract all the content values except the body from an SMS
467     * message.
468     */
469    private ContentValues extractContentValues(SmsMessage sms) {
470        // Store the message in the content provider.
471        ContentValues values = new ContentValues();
472
473        values.put(Inbox.ADDRESS, sms.getDisplayOriginatingAddress());
474
475        // Use now for the timestamp to avoid confusion with clock
476        // drift between the handset and the SMSC.
477        values.put(Inbox.DATE, new Long(System.currentTimeMillis()));
478        values.put(Inbox.PROTOCOL, sms.getProtocolIdentifier());
479        values.put(Inbox.READ, 0);
480        values.put(Inbox.SEEN, 0);
481        if (sms.getPseudoSubject().length() > 0) {
482            values.put(Inbox.SUBJECT, sms.getPseudoSubject());
483        }
484        values.put(Inbox.REPLY_PATH_PRESENT, sms.isReplyPathPresent() ? 1 : 0);
485        values.put(Inbox.SERVICE_CENTER, sms.getServiceCenterAddress());
486        return values;
487    }
488
489    /**
490     * Displays a class-zero message immediately in a pop-up window
491     * with the number from where it received the Notification with
492     * the body of the message
493     *
494     */
495    private void displayClassZeroMessage(Context context, SmsMessage sms) {
496        // Using NEW_TASK here is necessary because we're calling
497        // startActivity from outside an activity.
498        Intent smsDialogIntent = new Intent(context, ClassZeroActivity.class)
499                .putExtra("pdu", sms.getPdu())
500                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
501                          | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
502
503        context.startActivity(smsDialogIntent);
504    }
505
506    private void registerForServiceStateChanges() {
507        Context context = getApplicationContext();
508        unRegisterForServiceStateChanges();
509
510        IntentFilter intentFilter = new IntentFilter();
511        intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
512        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
513            Log.v(TAG, "registerForServiceStateChanges");
514        }
515
516        context.registerReceiver(SmsReceiver.getInstance(), intentFilter);
517    }
518
519    private void unRegisterForServiceStateChanges() {
520        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
521            Log.v(TAG, "unRegisterForServiceStateChanges");
522        }
523        try {
524            Context context = getApplicationContext();
525            context.unregisterReceiver(SmsReceiver.getInstance());
526        } catch (IllegalArgumentException e) {
527            // Allow un-matched register-unregister calls
528        }
529    }
530
531}
532
533
534