Android TelephonyManager 不能与 android 工作室模拟器一起使用?

Android TelephonyManager doesn't work with android studio simulator?

我正在使用这个简单的代码来检索一些 phone 设备数据,但出于某种原因,我在模拟器上打开应用程序时,它会弹出一条消息,说 "Unfortunately *APP NAME* has closed" 然后它关闭应用程序。

这是我使用的代码:

TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String IMEINumber=tm.getDeviceId();

我编写该代码只是为了测试 Telephonymanager 方法,但除以下内容外没有任何效果: "getPhoneType();"

有什么问题吗?也许是因为我在 android 工作室模拟器上运行它?

它说的问题:getDeviceId: Neither user 10058 nor current process has android.permission.READ_PHONE_STATE 虽然我在清单中添加了权限:

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

(申请部分以上)

感谢您的帮助

你是 运行 Android M 吗?如果是这样,这是因为在 manifest 中声明 permissions 是不够的。对于某些 permissions,您必须在 run-time 中明确询问用户:

Run time Permission 检查此 Link

代码段。

Define this Globally in your Activity.

private static final int PERMISSION_REQUEST_CODE = 1;

Do this stuff in onCreate.

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(TestingActivity.this,
        Manifest.permission.READ_PHONE_STATE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(TestingActivity.this,
            Manifest.permission.READ_PHONE_STATE)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(TestingActivity.this,
                new String[]{Manifest.permission.READ_PHONE_STATE},
                PERMISSION_REQUEST_CODE);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

Finally overrride onRequestPermissionsResult.

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay!

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}