1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.apis.os; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.database.Cursor; 23 import android.net.Uri; 24 import android.os.Bundle; 25 import android.provider.ContactsContract; 26 import android.telephony.SmsMessage; 27 28 public class SmsMessageReceiver extends BroadcastReceiver { 29 /** Tag string for our debug logs */ 30 private static final String TAG = "SmsMessageReceiver"; 31 32 @Override 33 public void onReceive(Context context, Intent intent) { 34 Bundle extras = intent.getExtras(); 35 if (extras == null) 36 return; 37 38 Object[] pdus = (Object[]) extras.get("pdus"); 39 40 for (int i = 0; i < pdus.length; i++) { 41 SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]); 42 String fromAddress = message.getOriginatingAddress(); 43 String fromDisplayName = fromAddress; 44 45 Uri uri; 46 String[] projection; 47 48 // If targeting Donut or below, use 49 // Contacts.Phones.CONTENT_FILTER_URL and 50 // Contacts.Phones.DISPLAY_NAME 51 uri = Uri.withAppendedPath( 52 ContactsContract.PhoneLookup.CONTENT_FILTER_URI, 53 Uri.encode(fromAddress)); 54 projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME }; 55 56 // Query the filter URI 57 Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); 58 if (cursor != null) { 59 if (cursor.moveToFirst()) 60 fromDisplayName = cursor.getString(0); 61 62 cursor.close(); 63 } 64 65 // Trigger the main activity to fire up a dialog that shows/reads the received messages 66 Intent di = new Intent(); 67 di.setClass(context, SmsReceivedDialog.class); 68 di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); 69 di.putExtra(SmsReceivedDialog.SMS_FROM_ADDRESS_EXTRA, fromAddress); 70 di.putExtra(SmsReceivedDialog.SMS_FROM_DISPLAY_NAME_EXTRA, fromDisplayName); 71 di.putExtra(SmsReceivedDialog.SMS_MESSAGE_EXTRA, message.getMessageBody().toString()); 72 context.startActivity(di); 73 74 // For the purposes of this demo, we'll only handle the first received message. 75 break; 76 } 77 } 78 } 79