0

I want to receive new SMS in same activity. For that i tried following code. Can anyone tell me what is wrong in my code?

My Code:

public BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("LOG", "message recived");

        }
    };
@Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(this.mReceiver);
    }

And in Manifest file add this permission :

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

thank you in advance.

Saman
  • 2,506
  • 4
  • 22
  • 41
  • @Pavneet_Singh I just need `log` at this step.The code is complete – Saman Jun 02 '17 at 13:56
  • Do you have the `` element in the right spot in the manifest; outside of the `` tags? If you're running on Marshmallow or above, and your `targetSdkVersion` is >=23, are you requesting the permission at runtime? Does your device have any additional settings/permissions that restrict third-party apps from receiving SMS by default? Is your `Activity` running in the foreground when the SMS is received? – Mike M. Jun 02 '17 at 22:19
  • My target sdk is 14 but device i used for test has sdk 24 . Am i need request permission at run time..!? – Saman Jun 02 '17 at 22:37
  • If your `targetSdkVersion` is actually <23, then no, it would be granted at installation. Do note, though, if you're using Android Studio, the `targetSdkVersion` is set in the build.gradle file. Any value you might have for that in the manifest will be overridden. If your device is 24, then you can just check your app's page in Settings to determine the permission state. – Mike M. Jun 02 '17 at 22:42
  • @MikeM. Sorry my target sdk is 25 and minimum sdk is 17 – Saman Jun 02 '17 at 22:52
  • Then, yeah, you'd have to request that at runtime. https://developer.android.com/training/permissions/requesting.html If you just wanna test your Receiver, though, before you start with all the permissions stuff, you should be able to manually turn on that permission in the app's Settings. Alternatively, drop the `targetSdkVersion` to 22 or below temporarily. – Mike M. Jun 02 '17 at 22:57
  • @MikeM. Very thanks .I had not thought at all about permission.One another question if i set min sdk 17 for device with sdk below 23 this permission granted at installation? – Saman Jun 02 '17 at 23:10
  • Runtime requests for dangerous permissions were introduced in 23. Any device <23 will have them granted at installation, no matter what you've set for `targetSdkVersion`/`minSdkVersion`. That is, before 23, it wouldn't even know about runtime requests. – Mike M. Jun 02 '17 at 23:20

0 Answers0