Search code examples
androidcordovacordova-plugins

Issues with android permissions in Cordova


I'm working on a demo app for android that needs to get information about the phone, the SIM, the network, etc.. I put all the code in a plugin and my Java function that that retrieves the SIM info looks like this:


  private boolean getSIMInfo(CallbackContext cbc) throws JSONException {

    // tm is a TelephonyManager instantiated in initialize
    JSONObject res = new JSONObject()
      .put("carrierID", tm.getSimCarrierId()) 
      .put("carrierName", tm.getSimCarrierIdName())
      .put("countryIso", tm.getSimCountryIso())
      .put("operator", tm.getSimOperator())
      .put("operatorName", tm.getSimOperatorName())
      .put("state", tm.getSimState())
      .put("msisdn", tm.getLine1Number()) // <== Requires permission
      ;
    cbc.success(res);
    return true;
  }

As long as I dont call getLine1Number() everything goes fine.

getLine1Number() requires either android.permission.READ_PHONE_STATE or a.p.READ_SMS or a.p.READ_PHONE_NUMBERS to be set. I first declared a.p.READ_PHONE_STATE in plugin's plugin.xml and I checked it was injected into AndroidManifest.xml.

The platform part of the plugin.xml looks like this:

  <platform name="android">

    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="TelPlugin">
        <param name="android-package" value="org.buguigny.CordovaPlugin.TelPlugin"/>
      </feature>
    </config-file>

    <config-file parent="/*" target="AndroidManifest.xml" />
    <config-file target="AndroidManifest.xml" parent="/*">
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    </config-file>
    <source-file src="src/TelPlugin.java" target-dir="src/org/buguigny/CordovaPlugin/TelPlugin" />

  </platform>`

Upon execution I get the error:

getLine1NumberForDisplay: Neither user 10190 nor current process has
   android.permission.READ_PHONE_STATE, android.permission.READ_SMS, or
   android.permission.READ_PHONE_NUMBERS

I tried with the other permissions: same error.

Any idea what I'm doing wrong ?


Solution

  • On Android >=6.0, Android app should request permission runtime.

    So in Cordova, you can use the permission plugin like following

    permissions.requestPermission(permissions.READ_PHONE_STATE, success, error);
    
    function error() {
      console.warn('Camera permission is not turned on');
    }
    
    function success( status ) {
      if( !status.hasPermission ) error();
    }