Search code examples
androidsmsandroid-7.0-nougatsmsmanagerandroid-7.1-nougat

How to receive sms in android API 25 (Nougat)


I have been using these code to receive sms in actual device android 4.2 and it was working fine, Now I came to know about new permission module so this code in android 7 nougat not working for me.

public class sms extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    if (bundle != null) {
        Object[] smsExtra = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[smsExtra.length];

        for (int i = 0; i < msgs.length; i++) {
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
            String body = sms.getMessageBody().toString();
            String sender = sms.getOriginatingAddress().toString();
            Toast.makeText(context, "From :"+sender+"\n"+"body:"+body, Toast.LENGTH_LONG).show();


        }
    }
}

}

I found this about marshmallow that there is run time permission required, But i don't get it how and where to add it in my code so that it work in Nougat and below apis.

// in manifest.xml

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

Solution

  • try this to read sms permisson runtime

    requestSmsPermission();
    
    private void requestSmsPermission() {
        String permission = Manifest.permission.READ_SMS;
        int grant = ContextCompat.checkSelfPermission(this, permission);
        if (grant != PackageManager.PERMISSION_GRANTED) {
            String[] permission_list = new String[1];
            permission_list[0] = permission;
            ActivityCompat.requestPermissions(this, permission_list, 1);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                                                Toast.makeText(AccountClass.this,"permission granted", Toast.LENGTH_SHORT).show();
    
    
            } else {
                Toast.makeText(AccountClass.this,"permission not granted", Toast.LENGTH_SHORT).show();
            }
        }
    
    }