/** * read sms, {@link Manifest.permission#READ_SMS} * in MEIZU 5.0~6.0, just according normal phone request * in XIAOMI 6.0~, need force judge * in XIAOMI 5.0~6.0, not test!!! * * @param activity * @return true if success * @throws Exception */ private static boolean checkReadSms(Context activity) throws Exception { Cursor cursor = activity.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, null); if (cursor != null) { if (ManufacturerSupportUtil.isForceManufacturer()) { if (isNumberIndexInfoIsNull(cursor, cursor.getColumnIndex(Telephony.Sms.DATE))) { cursor.close(); return false; } } cursor.close(); return true; } else { return false; } }
/** * 包访问级别:提高性能 * 从接收者中得到短信验证码 * * @param intent */ void getSmsCodeFromReceiver(Intent intent) { SmsMessage[] messages = null; if (Build.VERSION.SDK_INT >= 19) { messages = android.provider.Telephony.Sms.Intents.getMessagesFromIntent(intent); if (messages == null) return; } else { messages = getSmsUnder19(intent); if (messages == null) return; } if (messages.length > 0) { for (int i = 0; i < messages.length; i++) { SmsMessage sms = messages[i]; String smsSender = sms.getOriginatingAddress(); String smsBody = sms.getMessageBody(); if (checkSmsSender(smsSender) && checkSmsBody(smsBody)) { String smsCode = parseSmsBody(smsBody); sendMsg2Register(OBSERVER_SMS_CODE_MSG, smsCode); break; } } } }
/** * 包访问级别:提高性能 * 从内容观察者得到短信验证码 * * @param cursor */ void getSmsCodeFromObserver(Cursor cursor) { if (cursor == null) return; while (cursor.moveToNext()) { String address = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS)); String smsBody = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY)); if (checkSmsSender(address) && checkSmsBody(smsBody)) { String smsCode = parseSmsBody(smsBody); sendMsg2Register(RECEIVER_SMS_CODE_MSG, smsCode); break; } } closeCursor(cursor); }
private boolean isRelevant(Context context, Intent intent) { if (!ApplicationMigrationService.isDatabaseImported(context)) { return false; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) && Util.isDefaultSmsProvider(context)) { return false; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && TextSecurePreferences.isInterceptAllMmsEnabled(context)) { return true; } return false; }
@Override public void onReceive(Context context, Intent intent) { Log.w(TAG, "Got MMS broadcast..." + intent.getAction()); if ((Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION.equals(intent.getAction()) && Util.isDefaultSmsProvider(context)) || (Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) && isRelevant(context, intent))) { Log.w(TAG, "Relevant!"); int subscriptionId = intent.getExtras().getInt("subscription", -1); ApplicationContext.getInstance(context) .getJobManager() .add(new MmsReceiveJob(context, intent.getByteArrayExtra("data"), subscriptionId)); abortBroadcast(); } }
/** * read sms, {@link android.Manifest.permission#READ_SMS} * in MEIZU 5.0~6.0, just according normal phone request * in XIAOMI 6.0~, need force judge * in XIAOMI 5.0~6.0, not test!!! * * @param activity * @return true if success * @throws Exception */ private static boolean checkReadSms(Activity activity) throws Exception { Cursor cursor = activity.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, null); if (cursor != null) { if (ManufacturerSupportUtil.isForceManufacturer()) { if (isNumberIndexInfoIsNull(cursor, cursor.getColumnIndex(Telephony.Sms.DATE))) { cursor.close(); return false; } } cursor.close(); return true; } else { return false; } }
/** * 新增短信记录代理信息 **/ private void insertSmsLog() { Cursor cursor = mContext.getContentResolver().query( Uri.parse(PhoneContactUtils.SMS_URI_ALL), new String[]{Telephony.Sms._ID, "read"}, null, null, "date DESC"); if (cursor == null || cursor.getCount() <= 0) return; while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(Telephony.Sms._ID)); SmsProxy msg = findSmsById(id); if (msg == null) { msg = new SmsProxy(); msg.setId(id); mSmsDao.insert(msg); } } cursor.close(); }
@Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) { String smsSender = ""; String smsBody = ""; for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { smsBody += smsMessage.getMessageBody(); } if (smsBody.startsWith(SmsHelper.SMS_CONDITION)) { Log.d(TAG, "Sms with condition detected"); Toast.makeText(context, "BroadcastReceiver caught conditional SMS: " + smsBody, Toast.LENGTH_LONG).show(); } Log.d(TAG, "SMS detected: From " + smsSender + " With text " + smsBody); } }
@TargetApi(19) public static void askForDefaultAppChange(Fragment fragment, int requestCode) { if (!isAvailable()) return; Context context = fragment.getContext().getApplicationContext(); String packageName; // current app package is already set as default if (isDefault(context)) { // get previously saved app package as default packageName = Settings.getStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE); } else { // get blacklist app package as default packageName = context.getPackageName(); // save current default sms app package to the settings String nativePackage = Telephony.Sms.getDefaultSmsPackage(context); if (nativePackage != null) { Settings.setStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE, nativePackage); } } // start sms app change dialog askForDefaultAppChange(fragment, packageName, requestCode); }
@Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) { MBApp application = MBApp.getApp(); Intent charChangedIntent = new Intent(application, IPCService.class); charChangedIntent.putExtra(IPCConstants.INTENT_TYPE, EventCategories.IPC_BLE_NOTIFICATION_CHARACTERISTIC_CHANGED); charChangedIntent.putExtra(IPCConstants.INTENT_CHARACTERISTIC_MESSAGE, Utils.makeMicroBitValue (EventCategories.SAMSUNG_DEVICE_INFO_ID, EventSubCodes.SAMSUNG_INCOMING_SMS)); application.startService(charChangedIntent); } }
private void initializeDefaultPreference() { if (VERSION.SDK_INT < VERSION_CODES.KITKAT) return; Preference defaultPreference = findPreference(KITKAT_DEFAULT_PREF); if (Util.isDefaultSmsProvider(getActivity())) { defaultPreference.setIntent(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_enabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_change_your_default_sms_app)); } else { Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getActivity().getPackageName()); defaultPreference.setIntent(intent); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_disabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_make_signal_your_default_sms_app)); } }
@GET @Path("conversations") @Secure public Response getConversations() { List<Conversation> conversations = new ArrayList<>(); Cursor cur = deskDroidService.getApplication().getContentResolver() .query(Telephony.Sms.Conversations.CONTENT_URI, null, null, null, null); while (cur.moveToNext()) { conversations.add(buildConversation(cur)); } cur.close(); Collections.sort(conversations, new ConversationComparator()); return Response.ok(new GenericEntity<List<Conversation>>(conversations) { }).build(); }
protected Intent getIntent(Context context) { Intent sendIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //At least KitKat String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context); //Need to change the build to API 19 sendIntent = new Intent(Intent.ACTION_SEND); if (defaultSmsPackageName != null) { sendIntent.setPackage(defaultSmsPackageName); } } else { sendIntent = new Intent(Intent.ACTION_VIEW); } sendIntent.setType(getMimeType()); return sendIntent; }
private Cursor countMsgsFrom(String phoneNumber) { String[] select = { Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY, }; String whereClause = Telephony.Sms.ADDRESS +" = '"+phoneNumber+"'"; Uri quri = Uri.parse("content://sms/inbox"); return getContentResolver().query(quri, select, // Columns to select whereClause, // Clause to filter results null, // Arguments for the whereClause null); }
static boolean isDefaultApp(final Context context) { // there is no default sms app before android 4.4 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return true; } try { // check if this is the default sms app. // If the device doesn't support Telephony.Sms (i.e. tablet) getDefaultSmsPackage() will // be null. final String smsPackage = Telephony.Sms.getDefaultSmsPackage(context); return smsPackage == null || smsPackage.equals(BuildConfig.APPLICATION_ID); } catch (SecurityException e) { // some samsung devices/tablets want permission GET_TASKS o.O Log.e(TAG, "failed to query default SMS app", e); return true; } }
private void registerReceiverIfNecessary(BroadcastReceiver receiver) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && getCurrentActivity() != null) { getCurrentActivity().registerReceiver( receiver, new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION) ); isReceiverRegistered = true; return; } if (getCurrentActivity() != null) { getCurrentActivity().registerReceiver( receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED") ); isReceiverRegistered = true; } }
@Override public void onReceive(Context context, Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { for (SmsMessage message : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { receiveMessage(message); } return; } try { final Bundle bundle = intent.getExtras(); if (bundle == null || ! bundle.containsKey("pdus")) { return; } final Object[] pdus = (Object[]) bundle.get("pdus"); for (Object pdu : pdus) { receiveMessage(SmsMessage.createFromPdu((byte[]) pdu)); } } catch (Exception e) { Log.e(SmsListenerPackage.TAG, e.getMessage()); } }
/** * Creates an intent that will allow to send an SMS to a phone number * * @param body The text to send * @param phoneNumbers The phone numbers to send the SMS to (or null if you don't want to specify it) * @return the intent */ public static Intent newSmsIntent(Context context, String body, String[] phoneNumbers) { Uri smsUri; if (phoneNumbers == null || phoneNumbers.length==0) { smsUri = Uri.parse("smsto:"); } else { smsUri = Uri.parse("smsto:" + Uri.encode(TextUtils.join(",", phoneNumbers))); } Intent intent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_SENDTO, smsUri); intent.setPackage(Telephony.Sms.getDefaultSmsPackage(context)); } else { intent = new Intent(Intent.ACTION_VIEW, smsUri); } if (body!=null) { intent.putExtra("sms_body", body); } return intent; }
@SuppressLint("NewApi") private boolean shareSMSKitKatOrAfter(Context context, String shareContent) { try { String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context); Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_TEXT, shareContent); if (defaultSmsPackageName != null) { // Can be null in case that there is no default, then the user would be able // to choose any app that support this intent. sendIntent.setPackage(defaultSmsPackageName); } context.startActivity(sendIntent); return true; } catch (Exception e) { return false; } }
@Override public void onReceive(Context context, Intent intent) { Log.w("MmsListener", "Got MMS broadcast..." + intent.getAction()); if (Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION.equals(intent.getAction()) || (Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) && isRelevant(context, intent))) { Log.w("MmsListener", "Relevant!"); ApplicationContext.getInstance(context) .getJobManager() .add(new MmsReceiveJob(context, intent.getByteArrayExtra("data"))); abortBroadcast(); } }
private void initializePlatformSpecificOptions() { PreferenceScreen preferenceScreen = getPreferenceScreen(); Preference defaultPreference = findPreference(KITKAT_DEFAULT_PREF); Preference allSmsPreference = findPreference(TextSecurePreferences.ALL_SMS_PREF); Preference allMmsPreference = findPreference(TextSecurePreferences.ALL_MMS_PREF); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ) { if (allSmsPreference != null) preferenceScreen.removePreference(allSmsPreference); if (allMmsPreference != null) preferenceScreen.removePreference(allMmsPreference); if (Util.isDefaultSmsProvider(getActivity())) { defaultPreference.setIntent(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_enabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_change_your_default_sms_app)); } else { Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getActivity().getPackageName()); defaultPreference.setIntent(intent); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_disabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_make_textsecure_your_default_sms_app)); } } else if (defaultPreference != null) { preferenceScreen.removePreference(defaultPreference); } }
private void restoreSms() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //the device runs on kitkat and above. if (!isDefaultSmsApp()) { showSimpleMessageBox(getString(R.string.msg_app_default_message_permission), new OnButtonClick() { @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onYesClick(MessageDialog messageDialog) { super.onYesClick(messageDialog); messageDialog.dismiss(); Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName()); startActivityForResult(intent, DEFAULT_MESSAGE_APP_REQUEST_CODE); } }); } else { //restore sms normally. restore(backupFileListAdapter.getSelectedSMSBrowser()); } } }
private void markMmsFailedToSend(Context context, Uri msgUri) { // https://github.com/qklabs/aosp-messenger/blob/master/src/com/android/mms/data/WorkingMessage.java#L1476-1476 try { PduPersister p = PduPersister.getPduPersister(context); // Move the message into MMS Outbox. A trigger will create an entry in // the "pending_msgs" table. p.move(msgUri, Telephony.Mms.Outbox.CONTENT_URI); // Now update the pending_msgs table with an error for that new item. ContentValues values = new ContentValues(1); values.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE, Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT); long msgId = ContentUris.parseId(msgUri); SqliteWrapper.update(context, mContentResolver, Telephony.MmsSms.PendingMessages.CONTENT_URI, values, Telephony.MmsSms.PendingMessages.MSG_ID + "=" + msgId, null); } catch (MmsException e) { // Not much we can do here. If the p.move throws an exception, we'll just // leave the message in the draft box. Log.e(TAG, "Failed to move message to outbox and mark as error: " + msgUri, e); } }
/** * Find all messages to be sent or downloaded before certain time. */ public Cursor getPendingMessages(long dueTime) { Uri.Builder uriBuilder = Telephony.MmsSms.PendingMessages.CONTENT_URI.buildUpon(); uriBuilder.appendQueryParameter("protocol", "mms"); String selection = "err_type" + " < ?" + " AND " + "due_time" + " <= ?"; String[] selectionArgs = new String[] { String.valueOf(10), String.valueOf(dueTime) }; return SqliteWrapper.query(mContext, mContentResolver, uriBuilder.build(), null, selection, selectionArgs, "due_time"); }
private void updateCanonicalAddressInDb(long id, String number) { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] updateCanonicalAddressInDb: id=" + id + ", number=" + number); } final ContentValues values = new ContentValues(); values.put(Telephony.CanonicalAddressesColumns.ADDRESS, number); final StringBuilder buf = new StringBuilder(Telephony.CanonicalAddressesColumns._ID); buf.append('=').append(id); final Uri uri = ContentUris.withAppendedId(sSingleCanonicalAddressUri, id); final ContentResolver cr = mContext.getContentResolver(); // We're running on the UI thread so just fire & forget, hope for the best. // (We were ignoring the return value anyway...) new Thread("updateCanonicalAddressInDb") { public void run() { cr.update(uri, values, buf.toString(), null); } }.start(); }
public static void insertCanonicalAddressInDb(final Context context, String number) { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] insertCanonicalAddressInDb: number=" + number); } final ContentValues values = new ContentValues(); values.put(Telephony.CanonicalAddressesColumns.ADDRESS, number); final ContentResolver cr = context.getContentResolver(); // We're running on the UI thread so just fire & forget, hope for the best. // (We were ignoring the return value anyway...) new Thread("insertCanonicalAddressInDb") { public void run() { cr.insert(sAllCanonical, values); } }.start(); }
@Override public int getItemViewType(int position) { // This method shouldn't be called if our cursor is null, since the framework should know // that there aren't any items to look at in that case MessageItem item = getItem(position); int boxId = item.getBoxId(); if (item.isSms()) { if (boxId == TextBasedSmsColumns.MESSAGE_TYPE_INBOX || boxId == TextBasedSmsColumns.MESSAGE_TYPE_ALL) { return INCOMING_ITEM; } else { return OUTGOING_ITEM; } } else { if (boxId == Telephony.Mms.MESSAGE_BOX_ALL || boxId == Telephony.Mms.MESSAGE_BOX_INBOX) { return INCOMING_ITEM; } else { return OUTGOING_ITEM; } } }
public static String getCursorSelection(SharedPreferences prefs, boolean blocked) { StringBuilder selection = new StringBuilder(); selection.append(Telephony.Threads.MESSAGE_COUNT); selection.append(" != 0"); selection.append(" AND "); selection.append(Telephony.Threads._ID); if (!blocked) selection.append(" NOT"); selection.append(" IN ("); Set<String> idStrings = getBlockedConversations(prefs); for (int i = 0; i < idStrings.size(); i++) { selection.append("?"); if (i < idStrings.size() - 1) { selection.append(","); } } selection.append(")"); return selection.toString(); }
@Override public void onReceive(Context context, Intent intent) { Log.w(TAG, "Got MMS broadcast..." + intent.getAction()); if ((Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION.equals(intent.getAction()) && Util.isDefaultSmsProvider(context)) || (Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) && isRelevant(context, intent))) { Log.w(TAG, "Relevant!"); ApplicationContext.getInstance(context) .getJobManager() .add(new MmsReceiveJob(context, intent.getByteArrayExtra("data"))); abortBroadcast(); } }
@SuppressLint("NewApi") private void invokeSMSIntent(String phoneNumber, String message) { Intent sendIntent; if ("".equals(phoneNumber) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this.cordova.getActivity()); sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_TEXT, message); if (defaultSmsPackageName != null) { sendIntent.setPackage(defaultSmsPackageName); } } else { sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", message); // See http://stackoverflow.com/questions/7242190/sending-sms-using-intent-does-not-add-recipients-on-some-devices sendIntent.putExtra("address", phoneNumber); sendIntent.setData(Uri.parse("smsto:" + Uri.encode(phoneNumber))); } this.cordova.getActivity().startActivity(sendIntent); }
private void markMessageRead(Context context, String number, String body) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT || !Telephony.Sms.getDefaultSmsPackage(context).equals(context.getPackageName())) return; // if not default SMS App -> cant mark as read on KitKat+ Uri uri = Uri.parse("content://sms/inbox"); Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); try { while (cursor.moveToNext()) { if ((cursor.getString(cursor.getColumnIndex("address")).equals(number)) && (cursor.getInt(cursor.getColumnIndex("read")) == 0)) { if (cursor.getString(cursor.getColumnIndex("body")).startsWith(body)) { String SmsMessageId = cursor.getString(cursor.getColumnIndex("_id")); ContentValues values = new ContentValues(); values.put("read", true); context.getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=" + SmsMessageId, null); return; } } } } catch (Exception e) { Log.e("Mark Read", "Error in Read: " + e.toString()); } }
private static ContentValues serializeMessage(SmsMessageData messageData) { ContentValues values = MapUtils.contentValuesForSize(7); values.put(Telephony.Sms.ADDRESS, messageData.getSender()); values.put(Telephony.Sms.BODY, messageData.getBody()); values.put(Telephony.Sms.DATE, messageData.getTimeReceived()); values.put(Telephony.Sms.DATE_SENT, messageData.getTimeSent()); values.put(Telephony.Sms.READ, messageData.isRead() ? 1 : 0); values.put(Telephony.Sms.SEEN, 1); // Always mark messages as seen // Also write subscription ID (aka SIM card number) on Android 5.1+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { values.put(Telephony.Sms.SUBSCRIPTION_ID, messageData.getSubId()); } return values; }
public static Uri writeMessage(Context context, SmsMessageData messageData) { ContentResolver contentResolver = context.getContentResolver(); Uri uri = contentResolver.insert(Telephony.Sms.CONTENT_URI, serializeMessage(messageData)); long id = -1; if (uri != null) { id = ContentUris.parseId(uri); } // An ID of 0 when writing to the SMS inbox could mean we don't have the // OP_WRITE_SMS permission. See ContentProvider#rejectInsert(Uri, ContentValues). // Another explanation would be that this is actually the first message written. // Because we check for permissions before calling this method, we can assume // it's the latter case. if (id == 0) { Xlog.w("Writing to SMS inbox returned row 0"); return uri; } else if (id < 0) { Xlog.e("Writing to SMS inbox failed (unknown reason)"); throw new DatabaseException("Failed to write message to SMS inbox"); } else { return uri; } }
/** * Fires up an intent with the request to send an sms to the msisdn that of * this Phone * * @param context The context to use * @throws ActivityNotFoundException Throw if there is no installed * application to handle our request */ @SuppressLint("NewApi") public void sendText(Context context) throws ActivityNotFoundException { if (Utils.hasKitKat()) { // forward to the default sms app if we're in kitkat String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context); Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(getNumber()))); if (defaultSmsPackageName != null) { sendIntent.setPackage(defaultSmsPackageName); } context.startActivity(sendIntent); } else { Intent textIntent = new Intent(); textIntent.setAction(Intent.ACTION_VIEW); textIntent.setData(Uri.fromParts("sms", getNumber(), null)); context.startActivity(textIntent); } }
@Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String incoming_number; if (bundle != null) { //---retrieve the SMS message received--- try { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); incoming_number = msgs[i].getOriginatingAddress(); checkNumber(incoming_number); } } catch (Exception e) { Log.d(TAG, e.getMessage()); } } } }