gpt4 book ai didi

Android TelephonyManager 不适用于 android studio 模拟器?

转载 作者:行者123 更新时间:2023-11-29 17:19:01 25 4
gpt4 key购买 nike

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

这是我正在使用的代码:

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

我编写该代码只是为了测试 Telephonymanager方法,但没有任何效果,除了: "getPhoneType();"
任何想法有什么问题?也许是因为我在我的 android studio 模拟器上运行它?

它说的问题: getDeviceId: Neither user 10058 nor current process has android.permission.READ_PHONE_STATE虽然我在 list 中添加了一个权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
(应用部分上方)

谢谢您的帮助

最佳答案

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

检查此Link对于 Run time Permission .

代码 fragment 。

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

关于Android TelephonyManager 不适用于 android studio 模拟器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com