Android TelephonyManager不能与android studio模拟器一起使用?

时间:2016-05-25 05:09:39

标签: android telephonymanager

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

这是我正在使用的代码:

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" />

(在申请部分之上)

谢谢你的帮助

1 个答案:

答案 0 :(得分:3)

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

中明确询问用户

点击Link查看Run time Permission

代码段。

  

Globally中定义此Activity

private static final int PERMISSION_REQUEST_CODE = 1;
  

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.
    }
}
  

最后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
    }
}