2012-03-19 139 views
8

我是新來的Android開發所以對不起,如果我問一個非常明顯的問題。對於我的應用程序,我想要使用客戶經理自動添加一個谷歌賬戶。我是否想要使用addAccount或addAccountExplicitly,假設帳戶名稱是「platinum」,密碼是「software」,我該如何解決這個問題。通過賬戶經理添加賬戶

回答

12

試試這個:

需要

權限:

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

AuthenticatorActivity.java

public class SleepyAccountAuthenticatorActivity extends AccountAuthenticatorActivity 
{ 
protected void onCreate(Bundle icicle) 
{ 
    super.onCreate(icicle); 
    setContentView(R.layout.new_account); 
    final Button done = (Button) findViewById(R.id.new_account_done); 
    final EditText server = (EditText) findViewById(R.id.new_account_server); 
    final EditText username = (EditText) findViewById(R.id.new_account_username); 
    final EditText password = (EditText) findViewById(R.id.new_account_password); 
    final Activity self = this; 
    done.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) 
     { 
      //Account 
      Account account=new Account(username.getText(). 
      toString(), getString(R.string.ACCOUNT_TYPE)); 

      Bundle userdata = new Bundle(); 
      userdata.putString("SERVER", server.getText().toString()); 
      //AccountManager 
      AccountManager am = AccountManager.get(self); 

      if (am.addAccountExplicitly(account, password. 
      getText().toString(), userdata)) 
      { 
       Bundle result = new Bundle(); 
       result.putString(AccountManager.KEY_ACCOUNT_NAME, username.getText().toString()); 
       result.putString(AccountManager.KEY_ACCOUNT_TYPE,getString(R.string.ACCOUNT_TYPE)); 
       setAccountAuthenticatorResult(result); 
      } 
      finish(); 
     } 
    }); 
} 
} 

\水庫\ XML \ authenticator.xml

<?xml version="1.0" encoding="utf-8"?> 
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" 
android:accountType="com.yarin.AccountType" 
android:icon="@drawable/icon" 
android:smallIcon="@drawable/icon" 
android:label="@string/ACCOUNT_LABEL" 
android:accountPreferences="@xml/account_preferences" 
/> 
+0

@imran您可以發佈您的完整源代碼嗎?這也會對我有所幫助。 – 2012-07-19 07:48:48

+1

setAccountAuthenticatorResult是在AccountAuthenticatorActivity類中定義的方法,請參閱此處http://developer.android.com/reference/android/accounts/AccountAuthenticatorActivity.html – 2012-07-19 07:55:12

+0

並且佈局代碼在哪裏? – 2012-07-19 08:17:49