How can I add an Account with AddAccountExplicitly?

2.1k views Asked by At

I found many questions about this topic, without an an answer or with broken external link. I want to add an account in a simple way. The error is always the same: java.lang.SecurityException: caller uid xxxxx is different than the authenticator's uid (where I call addAccountExplicitly). But the account type is the same in code and xml, so... where I am doing wrong?

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

There are 2 answers

0
nibarius On

As the exception say your application and your authenticator must share the same UID. Normally all different apps get different UIDs so if you haven't specifically set up them to share UID they will have different UIDs.

You can check what UID your app have been assigned by looking at the ApplicationInfo.uid. You can get hold of ApplicationInfo by using getApplicationInfo() in PackageManager.

You can setup a shared UID by using the android:sharedUserId attribute in the manifest file for both your authenticator and your app.

0
marc On

I had the same problem as you. It turned out that I had not properly registered my authentication service in my applications manifest file:

<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>

Your intent filter name is defined by the android framework. So it has to be "android.accounts.AccountAuthenticator"