android.provider.Telephony Java Examples

The following examples show how to use android.provider.Telephony. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultSMSAppHelper.java    From BlackList with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: SmsReadTest.java    From AndPermission with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test() throws Throwable {
    String[] projection = new String[] {Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.PERSON,
        Telephony.Sms.BODY};
    Cursor cursor = mResolver.query(Telephony.Sms.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
        try {
            CursorTest.read(cursor);
        } finally {
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example #3
Source File: ReadSmsService.java    From AutoInputAuthCode with Apache License 2.0 6 votes vote down vote up
/**
 * 包访问级别:提高性能
 * 从接收者中得到短信验证码
 *
 * @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;
            }
        }
    }
}
 
Example #4
Source File: ReadSmsService.java    From AutoInputAuthCode with Apache License 2.0 6 votes vote down vote up
/**
 * 包访问级别:提高性能
 * 从内容观察者得到短信验证码
 *
 * @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);
}
 
Example #5
Source File: PermissionsChecker.java    From permissions4m with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #6
Source File: SmsHandlerHook.java    From XposedSmsCode with GNU General Public License v3.0 6 votes vote down vote up
private void beforeDispatchIntentHandler(XC_MethodHook.MethodHookParam param, int receiverIndex) {
    Intent intent = (Intent) param.args[0];
    String action = intent.getAction();

    // We only care about the initial SMS_DELIVER intent,
    // the rest are irrelevant
    if (!Telephony.Sms.Intents.SMS_DELIVER_ACTION.equals(action)) {
        return;
    }

    ParseResult parseResult = new CodeWorker(mAppContext, mPhoneContext, intent).parse();
    if (parseResult != null) {// parse succeed
        if (parseResult.isBlockSms()) {
            XLog.d("Blocking code SMS...");
            deleteRawTableAndSendMessage(param.thisObject, param.args[receiverIndex]);
            param.setResult(null);
        }
    }
}
 
Example #7
Source File: SmsListenerModule.java    From react-native-android-sms-listener with MIT License 6 votes vote down vote up
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;
    }
}
 
Example #8
Source File: SmsReceiver.java    From react-native-android-sms-listener with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example #9
Source File: CallAndSmsDao.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
/**
 * 新增短信记录代理信息
 **/
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();
}
 
Example #10
Source File: Utils.java    From MockSMS with Apache License 2.0 6 votes vote down vote up
public static HashMap getSMSAppsContent(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = new Intent(Telephony.Sms.Intents.SMS_DELIVER_ACTION);
    List<ResolveInfo> smsReceivers = packageManager.queryBroadcastReceivers(intent, 0);
    HashMap<String, String> receivers = new HashMap<>();
    for (ResolveInfo resolveInfo : smsReceivers) {
        final ActivityInfo activityInfo = resolveInfo.activityInfo;
        if (activityInfo == null) {
            continue;
        }
        if (!Manifest.permission.BROADCAST_SMS.equals(activityInfo.permission)) {
            continue;
        }
        final String packageName = activityInfo.packageName;
        if (!receivers.containsKey(packageName)) {
            final String applicationName = resolveInfo.loadLabel(packageManager).toString();
            receivers.put(packageName, applicationName);
        }
    }
    return receivers;
}
 
Example #11
Source File: MainActivity.java    From MockSMS with Apache License 2.0 6 votes vote down vote up
void startSMSWork(View view) {
    DEF_PKG = Telephony.Sms.getDefaultSmsPackage(getApplicationContext());

    boolean tic = messageMain.getText().length() > 0;
    boolean tac = contactView.getText().length() >= 3;

    if (!tic) {
        Toast.makeText(getBaseContext(), "You need a message to save " + new String(Character.toChars(128530)), Toast.LENGTH_SHORT).show();
        return;
    }
    if (!tac) {
        Toast.makeText(getBaseContext(), "Invalid Phone Number " + new String(Character.toChars(128530)), Toast.LENGTH_SHORT).show();
        return;
    }
    Snackbar.make(view, "Crafting SMS using given details " + new String(Character.toChars(128517)), Snackbar.LENGTH_SHORT).show();
    // can't write toe :-(
    if (Telephony.Sms.getDefaultSmsPackage(getApplicationContext()).equals(getPackageName())) {
        doCreateSmsAndChangeDef();
    } else {
        Intent localIntent = new Intent("android.provider.Telephony.ACTION_CHANGE_DEFAULT");
        localIntent.putExtra("package", getPackageName());
        startActivityForResult(localIntent, CHANGE_FROM_DEF);
    }
}
 
Example #12
Source File: InboxSmsLoader.java    From NekoSMS with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: MainActivity.java    From MockSMS with Apache License 2.0 6 votes vote down vote up
void startSMSWork() {
    DEF_PKG = Telephony.Sms.getDefaultSmsPackage(getApplicationContext());

    boolean tic = messageMain.getText().length() > 0;
    boolean tac = contactView.getText().length() >= 3;

    if (!tic) {
        Toast.makeText(getBaseContext(), "You need a message to save " + new String(Character.toChars(128530)), Toast.LENGTH_SHORT).show();
        return;
    }
    if (!tac) {
        Toast.makeText(getBaseContext(), "Invalid Phone Number " + new String(Character.toChars(128530)), Toast.LENGTH_SHORT).show();
        return;
    }
    // can't write toe :-(
    if (Telephony.Sms.getDefaultSmsPackage(getApplicationContext()).equals(getPackageName())) {
        doCreateSmsAndChangeDef();
    } else {
        Intent localIntent = new Intent("android.provider.Telephony.ACTION_CHANGE_DEFAULT");
        localIntent.putExtra("package", getPackageName());
        startActivityForResult(localIntent, CHANGE_FROM_DEF);
    }
}
 
Example #14
Source File: Utils.java    From MockSMS with Apache License 2.0 6 votes vote down vote up
public static HashMap getSMSAppsContent(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = new Intent(Telephony.Sms.Intents.SMS_DELIVER_ACTION);
    List<ResolveInfo> smsReceivers = packageManager.queryBroadcastReceivers(intent, 0);
    HashMap<String, String> receivers = new HashMap<>();
    for (ResolveInfo resolveInfo : smsReceivers) {
        final ActivityInfo activityInfo = resolveInfo.activityInfo;
        if (activityInfo == null) {
            continue;
        }
        if (!Manifest.permission.BROADCAST_SMS.equals(activityInfo.permission)) {
            continue;
        }
        final String packageName = activityInfo.packageName;
        if (!receivers.containsKey(packageName)) {
            final String applicationName = resolveInfo.loadLabel(packageManager).toString();
            receivers.put(packageName, applicationName);
        }
    }
    return receivers;
}
 
Example #15
Source File: SmsReadTester.java    From PermissionAgent with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean test() throws Throwable {
    String[] projection = new String[] {Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.PERSON,
        Telephony.Sms.BODY};
    Cursor cursor = mResolver.query(Telephony.Sms.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
        try {
            CursorTest.read(cursor);
        } finally {
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example #16
Source File: SmsReadTester.java    From PermissionAgent with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean test() throws Throwable {
    String[] projection = new String[] {Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.PERSON,
        Telephony.Sms.BODY};
    Cursor cursor = mResolver.query(Telephony.Sms.CONTENT_URI, projection, null, null, null);
    if (cursor != null) {
        try {
            CursorTest.read(cursor);
        } finally {
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example #17
Source File: MmsListener.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
@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();
  }
}
 
Example #18
Source File: MMSMonitor.java    From SmsMatrix with GNU General Public License v3.0 5 votes vote down vote up
public void startMMSMonitoring() {
    try {
        monitorStatus = false;
        if (!monitorStatus) {
            contentResolver.registerContentObserver(
                Uri.parse("content://mms"),
                true,
                mmsObserver
            );

            // Save the count of MMS messages on start-up.
            Uri uriMMSURI = Uri.parse("content://mms-sms");
            Cursor mmsCur = mainActivity.getContentResolver().query(
                uriMMSURI,
                null,
                Telephony.Mms.MESSAGE_BOX + " = " + Telephony.Mms.MESSAGE_BOX_INBOX,
                null,
                Telephony.Mms._ID
            );
            if (mmsCur != null && mmsCur.getCount() > 0) {
                mmsCount = mmsCur.getCount();
                Log.d(TAG, "Init MMSCount = " + mmsCount);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}
 
Example #19
Source File: Util.java    From BaseProject with Apache License 2.0 5 votes vote down vote up
/**
 * 导航(指示)用户去选择默认的短信程序
 * @param mContext
 */
@SuppressLint("NewApi")
public static void guide2ChooseDefSmsApp(Context mContext) {
    String myPackageName = mContext.getPackageName();
    if (!Telephony.Sms.getDefaultSmsPackage(mContext).equals(myPackageName)) {
        Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
        intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mContext.getPackageName());
        mContext.startActivity(intent);
    }
}
 
Example #20
Source File: BlacklistInterceptService.java    From MobileGuard with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    // get sms messages
    SmsMessage[] messages = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
    } else {
        messages = SmsUtils.getMessagesFromIntent(intent);
    }
    // check whether sender in blacklist
    BlacklistDao dao = new BlacklistDao(context);
    for (SmsMessage message: messages) {
        // get sender
        String sender = message.getOriginatingAddress();
        // select by phone
        BlacklistBean bean = dao.selectByPhone(sender);
        if(null == bean) {// not in blacklist
            continue;
        }
        // check intercept mode
        if((BlacklistDb.MODE_SMS & bean.getMode()) != 0) {// has sms mode, need intercept
            // abort sms
            abortBroadcast();
        }
    }

}
 
Example #21
Source File: OnboardingManager.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
public static void inviteSMSContact (Activity context, String phoneNumber, String message)
{

    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

        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, message);

        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);

    }
    else // For early versions, do what worked for you before.
    {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setType("vnd.android-dir/mms-sms");

        if (phoneNumber != null)
        smsIntent.putExtra("address",phoneNumber);
        smsIntent.putExtra("sms_body",message);

        context.startActivity(smsIntent);
    }
}
 
Example #22
Source File: SmsMmsPreferenceFragment.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private void initializePlatformSpecificOptions() {
  PreferenceScreen preferenceScreen    = getPreferenceScreen();
  Preference       defaultPreference   = findPreference(KITKAT_DEFAULT_PREF);
  Preference       allSmsPreference    = findPreference(SilencePreferences.ALL_SMS_PREF);
  Preference       allMmsPreference    = findPreference(SilencePreferences.ALL_MMS_PREF);
  Preference       manualMmsPreference = findPreference(MMS_PREF);

  if (VERSION.SDK_INT >= 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_tap_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_tap_to_make_silence_your_default_sms_app));
    }
  } else if (defaultPreference != null) {
    preferenceScreen.removePreference(defaultPreference);
  }

  if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && manualMmsPreference != null) {
    preferenceScreen.removePreference(manualMmsPreference);
  }
}
 
Example #23
Source File: InboxSmsLoader.java    From NekoSMS with GNU General Public License v3.0 5 votes vote down vote up
public static Uri writeMessage(Context context, SmsMessageData messageData) {
    if (!AppOpsUtils.noteOp(context, AppOpsUtils.OP_WRITE_SMS)) {
        throw new SecurityException("Do not have permissions to write SMS");
    }

    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;
    }
}
 
Example #24
Source File: SmsReader.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Completable waitToReceiveConfirmationSms(int waitingTimeoutSeconds,
                                         String requiredSender,
                                         int submissionId,
                                         SubmissionType submissionType) {
    AtomicReference<BroadcastReceiver> receiver = new AtomicReference<>();
    return Completable.fromPublisher(s -> {
                receiver.set(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        try {
                            if (isAwaitedSuccessMessage(intent, requiredSender,
                                    submissionId, submissionType)) {
                                s.onComplete();
                            }
                        } catch (Exception ex) {
                            s.onError(ex);
                        }
                    }
                });
                context.registerReceiver(receiver.get(),
                        new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION));
            }
    ).timeout(waitingTimeoutSeconds, TimeUnit.SECONDS, Schedulers.newThread(),
            Completable.error(new SmsRepository.ResultResponseException(
                    SmsRepository.ResultResponseIssue.TIMEOUT))
    ).doFinally(() -> {
        if (receiver.get() != null) {
            try {
                context.unregisterReceiver(receiver.get());
            } catch (Throwable t) {
                Log.d(TAG, t.getClass().getSimpleName() + " " + t.getMessage());
            }
        }
    });
}
 
Example #25
Source File: SMSShare.java    From react-native-share with MIT License 5 votes vote down vote up
@Override
protected String getPackage() {
    if (android.os.Build.VERSION.SDK_INT >= 19 ) {
        return Telephony.Sms.getDefaultSmsPackage(this.reactContext);
    }
    return PACKAGE;
}
 
Example #26
Source File: TelephonyHelper.java    From AndroidCommons with Apache License 2.0 5 votes vote down vote up
public static boolean canSendSms(Context context) {
    if (!canPerformCall(context)) {
        return false;
    }

    if (Build.VERSION.SDK_INT < 19) {
        return true;
    } else {
        String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context);
        return defaultSmsPackageName != null;
    }
}
 
Example #27
Source File: MmsListener.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
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 &&
        SilencePreferences.isInterceptAllMmsEnabled(context))
    {
      return true;
    }

    byte[] mmsData   = intent.getByteArrayExtra("data");
    PduParser parser = new PduParser(mmsData);
    GenericPdu pdu   = parser.parse();

    if (pdu == null || pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) {
      Log.w(TAG, "Received Invalid notification PDU");
      return false;
    }

    NotificationInd notificationPdu = (NotificationInd)pdu;

    if (notificationPdu.getSubject() == null)
      return false;

    return WirePrefix.isEncryptedMmsSubject(notificationPdu.getSubject().getString());
  }
 
Example #28
Source File: SmsConnSlot.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
        try {
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            SmsMessage[] msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                String msg_from = msgs[i].getOriginatingAddress();
                String msgBody = msgs[i].getMessageBody();
                if (!Utils.isBlank(smsInnerData.sender)) {
                    if (!PhoneNumberUtils.compare(context, msg_from, smsInnerData.sender)) {
                        continue;
                    }
                }
                if (!Utils.isBlank(smsInnerData.content)) {
                    if (!msgBody.contains(smsInnerData.content)) {
                        continue;
                    }
                }
                Bundle dynamics = new Bundle();
                dynamics.putString(SmsEventData.SenderDynamics.id, msg_from);
                dynamics.putString(SmsEventData.ContentDynamics.id, msgBody);
                changeSatisfiedState(true, dynamics);
                return;
            }
            changeSatisfiedState(false);
        } catch (Exception e) {
            Logger.d("Exception caught",e.getMessage());
        }
    }
}
 
Example #29
Source File: IncomingSMSPresenter.java    From microbit with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    if(!isRegistered) {
        microBitApp.registerReceiver(incomingSMSListener, new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION));

        if(telephonyPlugin != null) {
            CmdArg cmd = new CmdArg(0, "Registered Incoming SMS Alert");
            telephonyPlugin.sendCommandBLE(PluginService.TELEPHONY, cmd);
            //TODO: do we need to report registration status?
        }
        isRegistered = true;
    }
}
 
Example #30
Source File: CaptchaObserver.java    From sms-captcha with Apache License 2.0 5 votes vote down vote up
@Override
public void onChange(boolean selfChange, Uri uri) {
    if (!URI_SMS_INBOX_INSERT.equals(uri)) {
        return;
    }

    final Uri queryUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        queryUri = Telephony.Sms.Inbox.CONTENT_URI;
    } else {
        queryUri = Uri.parse(SMS_INBOX);
    }
    Cursor cursor = mContext.getContentResolver().query(queryUri, PROJECTION,
            mQuerySelection, null, Telephony.Sms._ID + " DESC");
    if (cursor == null) {
        return;
    }
    if (cursor.getCount() <= 0) {
        closeCursor(cursor);
        return;
    }
    cursor.moveToFirst();
    do {
        final String body = cursor.getString(cursor.getColumnIndex(BODY));
        final Matcher matcher = mCaptchaPattern.matcher(body);
        if (!matcher.find() || matcher.groupCount() != 1) {
            continue;
        }
        String code = matcher.group(1);
        if (TextUtils.isDigitsOnly(code)) {
            if (mCaptchaListener != null) {
                mCaptchaListener.onCaptchaReceived(code);
            }
            break;
        }
    } while (cursor.moveToNext());
    closeCursor(cursor);
}