Permissions

Add these two permissions in the Android Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

Read SMS from Inbox

Reading SMS from inbox is not a big task, but your user needs to allow it if you app is running on Marhmallow or more. if you app is below marshmallow, then you wont need it. But here we will write one code for both versions.

Ask for Permission

First we will check, if the permission is already granted it not.

private boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return checkSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
    } 
    return true;
}

Handling the result

Once the user agrees or denies the request, we will get a callback in the onRequestPermissionsResult method. If the permission is denied, for the time being we will open the permission area in the settings.

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, 
                                     permissions, grantResults);
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        if (REQUEST_READ_SMS_PERMISSION == requestCode) {
            Log.i(TAG, "REQUEST_READ_SMS_PERMISSION Permission Granted");
        }

    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
        if (REQUEST_READ_SMS_PERMISSION == requestCode) {
            // TODO REQUEST_READ_SMS_PERMISSION Permission is not Granted.
            // TODO Request Not Granted.

            // This code is for get permission from setting.
            final Intent i = new Intent();
            i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            i.setData(Uri.parse("package:" + getPackageName()));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(i);
        }
    }
}

Read SMS

This simple method reads the message and return in the form of a string

@NonNull
private List<String> readSMS() {
    Uri mSmsQueryUri = Uri.parse(INBOX_URI);
    List<String> messages = new ArrayList<String>();

    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(mSmsQueryUri, 
                                            null, null, null, null);
        if (cursor == null) {
            Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);
        }
        for (boolean hasData = cursor.moveToFirst(); 
                     hasData; 
                     hasData = cursor.moveToNext()) {
            messages.add(cursor.getString(cursor.getColumnIndexOrThrow("body")));
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        cursor.close();
    }
    return messages;
}

Read the incoming SMS

To read the incoming message you need to write a Broadcast Receiver like this..

package read_sms.coderzheaven.com.readsms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SMSBCReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get Bundle object contained in the SMS intent passed in
        Bundle bundle = intent.getExtras();
        SmsMessage[] smsm;
        String smsStr = "";
        if (null != bundle) {
            // Get the SMS message
            Object[] pduses = (Object[]) bundle.get("pdus");
            smsm = new SmsMessage[pduses.length];
            for (int i = 0; i < smsm.length; i++) {
                smsm[i] = SmsMessage.createFromPdu((byte[]) pduses[i]);
                smsStr += "Sent From: " + smsm[i].getOriginatingAddress();
                smsStr += "\r\nMessage: ";
                smsStr += smsm[i].getMessageBody().toString();
                smsStr += "\r\n";
            }
        }
    }
}

Don’t forget to declare it in the AndroidManifest

<receiver android:name=".SMSBCReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Source Code

You can download the complete Android Studio source code from here.

Send your comments to coderzheaven@gmail.com or comment below.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.