Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver and PHONE_STATE does not work

I am trying to use BroadcastReceiver with READ_PHONE_STATE permission. I ask user for a permission on the run (Android M), but after all I get following Permission Denial:

W/BroadcastQueue: Permission Denial: receiving Intent { act=android.intent.action.PHONE_STATE flg=0x10 (has extras) } to com.pb.qostest/.network.PhoneStateBroadcastReceiver requires android.permission.READ_PRIVILEGED_PHONE_STATE due to sender android (uid 1000)

For a Permission I am using a code from this link: https://stackoverflow.com/a/38764861

So far wanted my phone state BroadcastReceiver to just print something so it looks like this:

public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {   
         Log.d("RECEIEVER", "PhoneStateBroadcastReceiver Receiver started!");
    }
}

Anyway nothing is printed due to permission denial above.

And in manifest it is:

<receiver
    android:name=".network.PhoneStateBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>
...
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Any idea how should it look alike or what is the problem?

like image 677
shemekh Avatar asked Oct 29 '22 04:10

shemekh


1 Answers

To be able to detect phone call, you need:

1 in Manifest.xml, define your receiver and ask for PHONE_STATE permission:

<receiver android:name=".network.PhoneStateBroadcastReceiver">
<intent-filter>
  <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>
// ...
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2 add a class PhoneStateBroadcastReceiver which extends BroadcastReceiver and overwrite onReceive()

3 at runtime, request PHONE_STATE permission upfront

    ActivityCompat.requestPermissions(myMainActivity,
            new String[]{Manifest.permission.READ_PHONE_STATE},
            READ_PHONE_STATE_CODE);

and give it via the system dialog

4 make a phone call

You'll see the intent caught in onReceive():

intent: Intent { act=android.intent.action.READ_PHONE_STATE flg=0x10 cmp=com.myApp.network.PhoneStateBroadcastReceiver (has extras) }
Action: android.intent.action.PHONE_STATE

Hope it helps

like image 169
Alessio Avatar answered Nov 09 '22 06:11

Alessio