-->

How to get android phone user's google account

2019-03-02 08:35发布

问题:

So I am making mobile game with unity engine, think to release to android target.

Now my game will have my own custom highscore board, there I think when user earn score, game should send his identity nickname, score to server.

So for get his distinct name, I think to get his google account name. (of course I can choose option that receive user's input for his nickname, but well, tiresome)

I just only need email format's front part (i.e. username) Example, if user's google account is asdf@gmail.com , I want to extract only "asdf".

So, how to do it?

And is this good way for get his distinct nickname?

Thanks.


So I did like this, but does not work.

public class MainActivity extends UnityPlayerActivity implements        AndroidInterface{
private String usergoogleName;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  
    GetUserName();      
} 
public void GetUserName(){
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> username = new LinkedList<String>();

    for (Account account : accounts) {
        username.add(account.name);
    }
    usergoogleName = username.get(0);
    sendMessage("Main Camera", "JavaMsg", usergoogleName);
}

@Override
public void sendMessage(String target, String method, String params) {
    // TODO Auto-generated method stub
    UnityPlayer.UnitySendMessage(target, method, params);
}

and at unity side, I attached script to 'Main Camera' object and write,

public string name;
public void JavaMsg(string str){
    name = str;
}
void OnGUI(){
    GUI.Label(new Rect(100, 200, 300, 100), "google account name is " + name);
}

but when I run this at my phone after make .apk file, doesn't read account name.

What is wrong?

回答1:

try this

AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> username = new LinkedList<String>();

for (Account account : accounts) {
    username.add(account.name);
}

and add permission to android manifest

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


回答2:

If you have a string asdf@gmail.com and you want everything before the @ you can use .split();

String email = asdf@gmail.com
String[] parts = email.split("@");
String nickname = parts[0];