gpt4 book ai didi

java - 如何获取设备用户的电子邮件地址?

转载 作者:行者123 更新时间:2023-12-02 02:03:39 24 4
gpt4 key购买 nike

你能帮我解决这个代码吗?它应该从当前 Android 设备获取电子邮件地址,但每次都返回 null。我已经尝试过 this但每次仍然为空

 public String getUsername() {
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(getApplicationContext()).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
return possibleEmail;
}
}
return null;
}

这是我的 list 文件:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Upload FTP"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

最佳答案

下面的代码对我来说非常有用。您所要做的就是

在您的 OnCreate() 中包含以下代码并根据您的要求进行调整

if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
}
}
else {
List<String> accountList = new ArrayList<String>();
Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
if (gmailPattern.matcher(account.name).matches()) {
accountsList.add(account.name);
Toast.makeText(getApplicationContext(), account.name, Toast.LENGTH_SHORT).show();
}
}

然后你必须在AndroidManifest.xml文件中添加GET_ACCOUNTS的权限

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

关于java - 如何获取设备用户的电子邮件地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173012/

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