如何使用AddAccountExplicitly添加帐户?

时间:2014-11-20 22:58:19

标签: android account accountmanager securityexception

我发现很多关于这个主题的问题,没有回答或外部链接断开。我想以简单的方式添加帐户。错误始终是相同的:java.lang.SecurityException:调用者uid xxxxx与身份验证者的uid不同(我在其中调用addAccountExplicitly)。但是代码和xml中的帐户类型是相同的,所以......我做错了吗?

public class AuthActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);

        AccountManager accountManager = AccountManager.get(this);
        final Account account = new Account("username", getString(R.string.account_type));
        accountManager.addAccountExplicitly(account, "password", null);
    }
}

<?xml version="1.0" encoding="utf-8"?>
<account-authenticator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="@string/account_type"
    android:icon="@drawable/ic_launcher"
    android:smallIcon="@drawable/ic_launcher"
    android:label="@string/name_app" />

2 个答案:

答案 0 :(得分:1)

我和你有同样的问题。事实证明,我没有在我的应用程序清单文件中正确注册我的身份验证服务:

<service
        android:name="com.example.android.syncadapter.AuthenticatorService">
    <intent-filter>
        <action android:name="android.accounts.AccountAuthenticator"/>
    </intent-filter>
    <meta-data
        android:name="android.accounts.AccountAuthenticator"
        android:resource="@xml/authenticator" />
</service>

您的意图过滤器名称由android框架定义。所以它必须是&#34; android.accounts.AccountAuthenticator&#34;

答案 1 :(得分:0)

例外情况说您的应用程序和身份验证者必须共享相同的UID。通常情况下,所有不同的应用都会获得不同的UID,因此,如果您没有专门设置它们来共享UID,则它们将具有不同的UID。

您可以通过查看ApplicationInfo.uid来查看您的应用已分配的内容。您可以使用getApplicationInfo()中的PackageManager来掌握ApplicationInfo。

您可以使用清单文件中android:sharedUserId属性为验证者和应用设置共享UID。