为什么即使我已经在代码中给出了所有权限,此代码也没有在模拟器中运行?

时间:2017-07-04 19:43:07

标签: java android android-studio

TelephonyManagerActivity.java

package com.lovepurohit.project15;

/**
* Program for telephony manager that means to access the details related
* to sim and phone number like IMEI number, Device type and many more
* <p/>
* For this we use TelephonyManagerActivity class which is in the package
* android.telephony.TelephonyManagerActivity;
*/


import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

//importing our new package
import android.telephony.TelephonyManager;

import android.widget.TextView;

/**
* Created by Love on 04-07-2017.
*/
public class TelephonyManagerActivity extends AppCompatActivity {
TextView textView;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manager_telephony);

    //Getting id
    textView = (TextView) findViewById(R.id.textView);


    //Accessing the service for performing operation related to telephony
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    /**
     * Getting the phone Type
     * whether phone is cdma or gsm
     */
    int type = tm.getPhoneType();

    //Getting other details like IMEI number and device id and etc
    String IMEINumber = tm.getDeviceId();

    //getting subscriber ID
    String subscriberID = tm.getDeviceId();

    //Getting Sim serial number
    String SIMSerialNumber = tm.getSimSerialNumber();

    //Getting network details
    String networkCountryISO = tm.getNetworkCountryIso();

    //Getting sim country info
    String SIMCountryISO = tm.getSimCountryIso();

    //Getting the software on which app is running
    String softwareVersion = tm.getDeviceSoftwareVersion();

    //Getting the voice mail number on which app is running
    String voiceMailNumber = tm.getVoiceMailNumber();

    String strPhoneType = "";
    switch (type) {
        case (TelephonyManager.PHONE_TYPE_CDMA):
            strPhoneType = "CDMA";
            break;

        case (TelephonyManager.PHONE_TYPE_GSM):
            strPhoneType = "GSM";
            break;

        case (TelephonyManager.PHONE_TYPE_NONE):
            strPhoneType = "NONE";
            break;

    }

    boolean isRoaming = tm.isNetworkRoaming();

    String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
}
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lovepurohit.project15">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="adndroid.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- Activity 25th our project -->
    <activity android:name=".SharedPreferences">
        <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <!-- Activity 26th of our project -->
    <activity android:name=".InternalStorage">
       <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <!-- Activity 27th of our project -->
    <activity android:name=".TelephonyManagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

</manifest>

我是否必须在真实设备上运行它?我已添加了所有权限,但它无法在模拟器中运行。我正在使用Marshmallow的API 23

2 个答案:

答案 0 :(得分:0)

您可以在onCreateMethod中执行此操作。我正在为WRITE_EXTERNAL_STORAGE做这件事你可以为READ_PHONE_STATE做同样的事情

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                   if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                       //Show Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Need Storage Permission");
                       builder.setMessage("We needs storage permission to proceed");
                       builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else if (permissionStatus.getBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,false)) {
                       //Previously Permission Request was cancelled with 'Dont Ask Again',
                       // Redirect to Settings after showing Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Storage Permission");
                       builder.setMessage("We need storage permission.");
                       builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               sentToSettings = true;
                               Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                               Uri uri = Uri.fromParts("package", getPackageName(), null);
                               intent.setData(uri);
                               startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                               Toast.makeText(getBaseContext(), "Go to Permissions to Grant Storage", Toast.LENGTH_LONG).show();
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else {
                       //just request the permission
                       ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                   }


                   SharedPreferences.Editor editor = permissionStatus.edit();
                   editor.putBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,true);
                   editor.commit();




               } else {
                   //You already have the permission, just go ahead.
                  textView = (TextView) findViewById(R.id.textView);


//Accessing the service for performing operation related to telephony
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

/**
 * Getting the phone Type
 * whether phone is cdma or gsm
 */
int type = tm.getPhoneType();

//Getting other details like IMEI number and device id and etc
String IMEINumber = tm.getDeviceId();

//getting subscriber ID
String subscriberID = tm.getDeviceId();

//Getting Sim serial number
String SIMSerialNumber = tm.getSimSerialNumber();

//Getting network details
String networkCountryISO = tm.getNetworkCountryIso();

//Getting sim country info
String SIMCountryISO = tm.getSimCountryIso();

//Getting the software on which app is running
String softwareVersion = tm.getDeviceSoftwareVersion();

//Getting the voice mail number on which app is running
String voiceMailNumber = tm.getVoiceMailNumber();

String strPhoneType = "";
switch (type) {
    case (TelephonyManager.PHONE_TYPE_CDMA):
        strPhoneType = "CDMA";
        break;

    case (TelephonyManager.PHONE_TYPE_GSM):
        strPhoneType = "GSM";
        break;

    case (TelephonyManager.PHONE_TYPE_NONE):
        strPhoneType = "NONE";
        break;

}

boolean isRoaming = tm.isNetworkRoaming();



 String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
                   }

 @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == REQUEST_PERMISSION_SETTING) {
           if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
              // Do the exact thing as in else condition above
           }
       }
   }



@Override
   public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       if (requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT) {
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // Do the exact thing as in else condition above
           } else {
               if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                   //Show Information about why you need the permission
                   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                   builder.setTitle("Need Storage Permission");
                   builder.setMessage("This app needs storage permission");
                   builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();


                           ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);


                       }
                   });
                   builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();
                       }
                   });
                   builder.show();
               } else {
                   Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
               }
           }
       }
   }

答案 1 :(得分:0)

您必须要求真实设备的运行时许可(请参阅https://developer.android.com/training/permissions/requesting.html?hl=en)。 仿真设备没有得到你要求的一些东西,可能会返回null,但其他东西应该给你价值。例如,在我的情况下,当我运行类似:

时,模拟设备ID返回00000000000
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        int duration = Toast.LENGTH_SHORT;

DeviceId = telephonyManager.getDeviceId() ;
String testToastInfo = DeviceId + "\n";

Toast.makeText(this,testToastInfo , duration).show();

希望这有帮助!