如何在安卓中获取手机号码



如何在安卓中获取手机号码?这是代码。但它不起作用

TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String mobileno = tm.getLine1Number();

谁能帮我解决这个问题。

您可以使用这些代码行从手机联系人选择器中获取手机号码。

try {
Intent i = new     Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, PICK_CONTACT);
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("TAG", "Pick Contact ERROR" + e.toString());
}

并使用OnActivityResult获取联系人并将其保存在您想要的任何位置(像这样)

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
String PhoneNumber =     cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String ContactName =     cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));

您可以尝试以下代码:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String number = tMgr.getLine1Number();

要使此代码正常工作,您需要权限:

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

最新更新