0

I have an android application that i need to receive sms and I found a certain tutorial that teaches how to do that but when I run it & I get android permission exception

FATAL EXCEPTION: main Process: androidreceivesms.javapapers.com.smsbroadcastreceiver, PID: 12206 java.lang.RuntimeException: Unable to start activity ComponentInfo{androidreceivesms.javapapers.com.smsbroadcastreceiver/androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider uri content://sms/inbox from pid=12206, uid=10061 requires android.permission.READ_SMS, or grantUriPermission() at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider uri content://sms/inbox from pid=12206, uid=10061 requires android.permission.READ_SMS, or grantUriPermission() at android.os.Parcel.readException(Parcel.java:1599) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135) at android.content.ContentProviderProxy.query(ContentProviderNative.java:421) at android.content.ContentResolver.query(ContentResolver.java:491) at android.content.ContentResolver.query(ContentResolver.java:434) at androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity.refreshSmsInbox(SmsActivity.java:52) at androidreceivesms.javapapers.com.smsbroadcastreceiver.SmsActivity.onCreate(SmsActivity.java:47) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Here is my AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SmsActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".SmsBroadcastReceiver" android:exported="true" >
        <intent-filter android:priority="999" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>

Here is my SmsActivity.java

public class SmsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private static SmsActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;

public static SmsActivity instance() {
    return inst;
}

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sms);
    smsListView = (ListView) findViewById(R.id.SMSList);
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
    smsListView.setAdapter(arrayAdapter);
    smsListView.setOnItemClickListener(this);

    refreshSmsInbox();
}

public void refreshSmsInbox() {
    ContentResolver contentResolver = getContentResolver();
    Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
    int indexBody = smsInboxCursor.getColumnIndex("body");
    int indexAddress = smsInboxCursor.getColumnIndex("address");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
    arrayAdapter.clear();
    do {
        String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                "\n" + smsInboxCursor.getString(indexBody) + "\n";
        arrayAdapter.add(str);
    } while (smsInboxCursor.moveToNext());
}

public void updateList(final String smsMessage) {
    arrayAdapter.insert(smsMessage, 0);
    arrayAdapter.notifyDataSetChanged();
}

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
    try {
        String[] smsMessages = smsMessagesList.get(pos).split("\n");
        String address = smsMessages[0];
        String smsMessage = "";
        for (int i = 1; i < smsMessages.length; ++i) {
            smsMessage += smsMessages[i];
        }

        String smsMessageStr = address + "\n";
        smsMessageStr += smsMessage;
        Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Here is my SmsBroadcastReceiver.java

public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String address = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + address + "\n";
            smsMessageStr += smsBody + "\n";
        }
        Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

        //this will update the UI with message
        SmsActivity inst = SmsActivity.instance();
        inst.updateList(smsMessageStr);
    }
}

}

Can anyone please help me because i have been stack here for a long time now? Any help will be appreciated thanks

N J
  • 27,217
  • 13
  • 76
  • 96
Nyerere
  • 29
  • 1
  • 2
  • 8
  • are you running it on marshmallow ? – Gautam Apr 14 '16 at 08:58
  • If you're running under KitKat, then the permissions issues addressed by the answers below are not the problem. They only apply to devices running Marshmallow. Are you sure that's the manifest under the `/src` folder? – Mike M. Apr 14 '16 at 09:43
  • I am running it on marshmallow ,sorry i didnt look carefully – Nyerere Apr 14 '16 at 09:45
  • 1
    Then check [this post](http://stackoverflow.com/questions/32635704/cant-get-the-permission) for information and links to examples of how to implement Marshmallow's runtime permissions. – Mike M. Apr 14 '16 at 09:47

2 Answers2

3

Looks like its because new permissions system in android 6 try to use it before work with sms

if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {}

and this if you dont have permissions

ActivityCompat.requestPermissions(SmsActivity.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);

I hope this helps

Alexander
  • 497
  • 6
  • 19
  • Please can you help me where exactly am i required to put the above checkpermission – Nyerere Apr 14 '16 at 09:16
  • From which package does the UnlockActivity.this come bse it seems it fail to resolve it with imports – Nyerere Apr 14 '16 at 09:41
  • And also can you help me with REQUEST_CODE_ASK_PERMISSIONS bse it can not be resolved from the code above – Nyerere Apr 14 '16 at 09:53
  • just declere it like final private int REQUEST_CODE_ASK_PERMISSIONS = 123; its app-defined int constant. The callback method gets the result of the request. Wait a 5 mins i will type code for exactly your app – Alexander Apr 14 '16 at 10:08
  • Aaaaah it works finally ,share a cake with me i was just required to declare permission from inside the app not Androidmanifest.xml – Nyerere Apr 14 '16 at 10:12
0

If you are running it on marshmallow, you need to request the permission to read the sms at the runtime.

Here's the official doc : http://developer.android.com/training/permissions/requesting.html

You have to check the permission using ContextCompat.checkSelfPermission function. Then, if you don't have the permission,

request it via ActivityCompat.requestPermissions method and implement

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) method to receive the user results.

Yash
  • 5,225
  • 4
  • 32
  • 65
  • Can you help me more on this ,because i'm still stuck on this - Can you help me with this from the code above that ihave posted? I mean how to implement this on my code – Nyerere Apr 14 '16 at 09:32
  • did you get your answer? or you need more help? – user4057066 Jan 11 '17 at 11:39