SmsReceiverService.java revision 159cc76b6fa80c9f20549d8168216a5226fd0a4a
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 if (mResultCode == SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE) {
288            mToastHandler.post(new Runnable() {
289                public void run() {
290                    Toast.makeText(SmsReceiverService.this, getString(R.string.fdn_check_failure),
291                            Toast.LENGTH_SHORT).show();
292                }
293            });
294        } else {
295            if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
296                Log.v(TAG, "handleSmsSent msg failed uri: " + uri);
297            }
298            Sms.moveMessageToFolder(this, uri, Sms.MESSAGE_TYPE_FAILED, error);
299            MessagingNotification.notifySendFailed(getApplicationContext(), true);
300            if (sendNextMsg) {
301                sendFirstQueuedMessage();
302            }
303        }
304    }
305
306    private void handleSmsReceived(Intent intent, int error) {
307        SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
308        Uri messageUri = insertMessage(this, msgs, error);
309
310        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
311            SmsMessage sms = msgs[0];
312            Log.v(TAG, "handleSmsReceived" + (sms.isReplace() ? "(replace)" : "") +
313                    " messageUri: " + messageUri +
314                    ", address: " + sms.getOriginatingAddress() +
315                    ", body: " + sms.getMessageBody());
316        }
317
318        if (messageUri != null) {
319            // Called off of the UI thread so ok to block.
320            MessagingNotification.blockingUpdateNewMessageIndicator(this, true, false);
321        }
322    }
323
324    private void handleBootCompleted() {
325        moveOutboxMessagesToQueuedBox();
326        sendFirstQueuedMessage();
327
328        // Called off of the UI thread so ok to block.
329        MessagingNotification.blockingUpdateNewMessageIndicator(this, true, false);
330    }
331
332    private void moveOutboxMessagesToQueuedBox() {
333        ContentValues values = new ContentValues(1);
334
335        values.put(Sms.TYPE, Sms.MESSAGE_TYPE_QUEUED);
336
337        SqliteWrapper.update(
338                getApplicationContext(), getContentResolver(), Outbox.CONTENT_URI,
339                values, "type = " + Sms.MESSAGE_TYPE_OUTBOX, null);
340    }
341
342    public static final String CLASS_ZERO_BODY_KEY = "CLASS_ZERO_BODY";
343
344    // This must match the column IDs below.
345    private final static String[] REPLACE_PROJECTION = new String[] {
346        Sms._ID,
347        Sms.ADDRESS,
348        Sms.PROTOCOL
349    };
350
351    // This must match REPLACE_PROJECTION.
352    private static final int REPLACE_COLUMN_ID = 0;
353
354    /**
355     * If the message is a class-zero message, display it immediately
356     * and return null.  Otherwise, store it using the
357     * <code>ContentResolver</code> and return the
358     * <code>Uri</code> of the thread containing this message
359     * so that we can use it for notification.
360     */
361    private Uri insertMessage(Context context, SmsMessage[] msgs, int error) {
362        // Build the helper classes to parse the messages.
363        SmsMessage sms = msgs[0];
364
365        if (sms.getMessageClass() == SmsMessage.MessageClass.CLASS_0) {
366            displayClassZeroMessage(context, sms);
367            return null;
368        } else if (sms.isReplace()) {
369            return replaceMessage(context, msgs, error);
370        } else {
371            return storeMessage(context, msgs, error);
372        }
373    }
374
375    /**
376     * This method is used if this is a "replace short message" SMS.
377     * We find any existing message that matches the incoming
378     * message's originating address and protocol identifier.  If
379     * there is one, we replace its fields with those of the new
380     * message.  Otherwise, we store the new message as usual.
381     *
382     * See TS 23.040 9.2.3.9.
383     */
384    private Uri replaceMessage(Context context, SmsMessage[] msgs, int error) {
385        SmsMessage sms = msgs[0];
386        ContentValues values = extractContentValues(sms);
387
388        values.put(Inbox.BODY, sms.getMessageBody());
389        values.put(Sms.ERROR_CODE, error);
390
391        ContentResolver resolver = context.getContentResolver();
392        String originatingAddress = sms.getOriginatingAddress();
393        int protocolIdentifier = sms.getProtocolIdentifier();
394        String selection =
395                Sms.ADDRESS + " = ? AND " +
396                Sms.PROTOCOL + " = ?";
397        String[] selectionArgs = new String[] {
398            originatingAddress, Integer.toString(protocolIdentifier)
399        };
400
401        Cursor cursor = SqliteWrapper.query(context, resolver, Inbox.CONTENT_URI,
402                            REPLACE_PROJECTION, selection, selectionArgs, null);
403
404        if (cursor != null) {
405            try {
406                if (cursor.moveToFirst()) {
407                    long messageId = cursor.getLong(REPLACE_COLUMN_ID);
408                    Uri messageUri = ContentUris.withAppendedId(
409                            Sms.CONTENT_URI, messageId);
410
411                    SqliteWrapper.update(context, resolver, messageUri,
412                                        values, null, null);
413                    return messageUri;
414                }
415            } finally {
416                cursor.close();
417            }
418        }
419        return storeMessage(context, msgs, error);
420    }
421
422    public static String replaceFormFeeds(String s) {
423        // Some providers send formfeeds in their messages. Convert those formfeeds to newlines.
424        return s.replace('\f', '\n');
425    }
426
427    private Uri storeMessage(Context context, SmsMessage[] msgs, int error) {
428        SmsMessage sms = msgs[0];
429
430        // Store the message in the content provider.
431        ContentValues values = extractContentValues(sms);
432        values.put(Sms.ERROR_CODE, error);
433        int pduCount = msgs.length;
434
435        if (pduCount == 1) {
436            // There is only one part, so grab the body directly.
437            values.put(Inbox.BODY, replaceFormFeeds(sms.getDisplayMessageBody()));
438        } else {
439            // Build up the body from the parts.
440            StringBuilder body = new StringBuilder();
441            for (int i = 0; i < pduCount; i++) {
442                sms = msgs[i];
443                body.append(sms.getDisplayMessageBody());
444            }
445            values.put(Inbox.BODY, replaceFormFeeds(body.toString()));
446        }
447
448        // Make sure we've got a thread id so after the insert we'll be able to delete
449        // excess messages.
450        Long threadId = values.getAsLong(Sms.THREAD_ID);
451        String address = values.getAsString(Sms.ADDRESS);
452        if (!TextUtils.isEmpty(address)) {
453            Contact cacheContact = Contact.get(address,true);
454            if (cacheContact != null) {
455                address = cacheContact.getNumber();
456            }
457        } else {
458            address = getString(R.string.unknown_sender);
459            values.put(Sms.ADDRESS, address);
460        }
461
462        if (((threadId == null) || (threadId == 0)) && (address != null)) {
463            threadId = Threads.getOrCreateThreadId(context, address);
464            values.put(Sms.THREAD_ID, threadId);
465        }
466
467        ContentResolver resolver = context.getContentResolver();
468
469        Uri insertedUri = SqliteWrapper.insert(context, resolver, Inbox.CONTENT_URI, values);
470
471        // Now make sure we're not over the limit in stored messages
472        Recycler.getSmsRecycler().deleteOldMessagesByThreadId(getApplicationContext(), threadId);
473
474        return insertedUri;
475    }
476
477    /**
478     * Extract all the content values except the body from an SMS
479     * message.
480     */
481    private ContentValues extractContentValues(SmsMessage sms) {
482        // Store the message in the content provider.
483        ContentValues values = new ContentValues();
484
485        values.put(Inbox.ADDRESS, sms.getDisplayOriginatingAddress());
486
487        // Use now for the timestamp to avoid confusion with clock
488        // drift between the handset and the SMSC.
489        values.put(Inbox.DATE, new Long(System.currentTimeMillis()));
490        values.put(Inbox.PROTOCOL, sms.getProtocolIdentifier());
491        values.put(Inbox.READ, 0);
492        values.put(Inbox.SEEN, 0);
493        if (sms.getPseudoSubject().length() > 0) {
494            values.put(Inbox.SUBJECT, sms.getPseudoSubject());
495        }
496        values.put(Inbox.REPLY_PATH_PRESENT, sms.isReplyPathPresent() ? 1 : 0);
497        values.put(Inbox.SERVICE_CENTER, sms.getServiceCenterAddress());
498        return values;
499    }
500
501    /**
502     * Displays a class-zero message immediately in a pop-up window
503     * with the number from where it received the Notification with
504     * the body of the message
505     *
506     */
507    private void displayClassZeroMessage(Context context, SmsMessage sms) {
508        // Using NEW_TASK here is necessary because we're calling
509        // startActivity from outside an activity.
510        Intent smsDialogIntent = new Intent(context, ClassZeroActivity.class)
511                .putExtra("pdu", sms.getPdu())
512                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
513                          | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
514
515        context.startActivity(smsDialogIntent);
516    }
517
518    private void registerForServiceStateChanges() {
519        Context context = getApplicationContext();
520        unRegisterForServiceStateChanges();
521
522        IntentFilter intentFilter = new IntentFilter();
523        intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
524        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
525            Log.v(TAG, "registerForServiceStateChanges");
526        }
527
528        context.registerReceiver(SmsReceiver.getInstance(), intentFilter);
529    }
530
531    private void unRegisterForServiceStateChanges() {
532        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
533            Log.v(TAG, "unRegisterForServiceStateChanges");
534        }
535        try {
536            Context context = getApplicationContext();
537            context.unregisterReceiver(SmsReceiver.getInstance());
538        } catch (IllegalArgumentException e) {
539            // Allow un-matched register-unregister calls
540        }
541    }
542
543}
544
545
546