dya*_* tb 2 android telephonymanager
如何使用Android Studio获取电话号码或SIM卡信息?(SIM卡1或2)
我使用了以下代码:
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phone_number.setText(tMgr.getLine1Number());
Run Code Online (Sandbox Code Playgroud)
而且我还在AndroidManifest中添加了权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Run Code Online (Sandbox Code Playgroud)
但是我应用的所有小工具都无法获取电话号码或始终生成空值。
这是我使用的build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
//noinspection GradleCompatible
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//noinspection UseOfBundledGooglePlayServices
implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.google.android.gms:play-services-auth:15.0.1'
}
Run Code Online (Sandbox Code Playgroud)
没有可靠的方法来从SIM卡获取电话号码。TelephonyManager从SIM卡读取电话号码,但由电信运营商读取,以将该信息添加到SIM卡中。
大多数电信运营商没有在SIM卡中添加此信息,因此其可靠性不够。
有一种使用Google Play服务获取电话号码的方法,但也不保证100%返回电话号码。您可以按照以下步骤进行操作。
在中添加以下依赖项build.gradle:
dependencies {
...
compile 'com.google.android.gms:play-services:11.6.0'
compile 'com.google.android.gms:play-services-auth:11.6.0'
}
Run Code Online (Sandbox Code Playgroud)
在中创建两个常量MainActivity.java:
private static final int PHONE_NUMBER_HINT = 100;
private final int PERMISSION_REQ_CODE = 200;
Run Code Online (Sandbox Code Playgroud)
在onclick您的按钮中添加以下内容:
final HintRequest hintRequest =
new HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build();
try {
final GoogleApiClient googleApiClient =
new GoogleApiClient.Builder(MainActivity.this).addApi(Auth.CREDENTIALS_API).build();
final PendingIntent pendingIntent =
Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);
startIntentSenderForResult(
pendingIntent.getIntentSender(),
PHONE_NUMBER_HINT,
null,
0,
0,
0
);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
添加onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHONE_NUMBER_HINT && resultCode == RESULT_OK) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
final String phoneNumber = credential.getId();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4112 次 |
| 最近记录: |