Как удалить гугл аккаунты на андроид версии пирога? - PullRequest
0 голосов
/ 03 октября 2019

Программно я хочу удалить аккаунт Google из раздела Аккаунт. Приведенный ниже код работает должным образом на устройствах с более низкой версией, но не работает на Oreo и более поздних версиях. Но я получаю это исключение

Причина: java.lang.SecurityException: uid 10117 не может удалить учетные записи типа: com.google

Вот мойкод:

final AccountManager accountManager = (AccountManager.get(getApplicationContext()));
        final Account[] accounts = accountManager.getAccountsByType("com.google");
        for (int index = 0; index < accounts.length; index++) {
            accountManager.removeAccount(accounts[index], null, null);
            // accountManager.removeAccountExplicitly(accounts[finalIndex]); Tried this line code as well.
          }

Я также дал приведенное ниже разрешение.

<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission
        android:name="android.permission.ACCOUNT_MANAGER"
        tools:ignore="ProtectedPermissions" />

После исследования я добавил этот коддля устройств Oreo и более поздних версий, но я не могу удалить учетную запись Google.

 public void requestGoogleAccountAccess() throws Exception {
        boolean googleAccountAccessGranted = GoogleAuthUtil.requestGoogleAccountsAccess(this);
        Log.i("", "googleAccountAccessGranted: " + googleAccountAccessGranted);
    }

    // exception handler after calling method above
    private void handleAuthResult(Throwable e) {
        if (e instanceof UserRecoverableAuthException) {
            UserRecoverableAuthException authException = (UserRecoverableAuthException) e;
            startActivityForResult(authException.getIntent(), 12);
        } else {
            Log.e("", "Cannot request Google Account Access", e);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 12) {
            Log.i("", "Google Auth Permission Result");

            if (resultCode == Activity.RESULT_CANCELED) {
                Log.w("", "User Cancelled Play Services Auth Request.");
            } else if (resultCode == Activity.RESULT_OK) {
                Log.d("", "User accepted Play Services Auth Request.");
                // call the following line again on a background thread. the call now returns a boolean instead of throwing an exception
                //  googleAccountAccessGranted = GoogleAuthUtil.requestGoogleAccountsAccess(this);
            }
        }
    }

Я добавил Authenticator

    public class Authenticator extends AbstractAccountAuthenticator {
        // Simple constructor
        public Authenticator(Context context) {
            super(context);
        }

        // Editing properties is not supported
        @Override
        public Bundle editProperties(
                AccountAuthenticatorResponse r, String s) {
            throw new UnsupportedOperationException();
        }

        // Don't add additional accounts
        @Override
        public Bundle addAccount(
                AccountAuthenticatorResponse r,
                String s,
                String s2,
                String[] strings,
                Bundle bundle) throws NetworkErrorException {
            return null;
        }

        // Ignore attempts to confirm credentials
        @Override
        public Bundle confirmCredentials(
                AccountAuthenticatorResponse r,
                Account account,
                Bundle bundle) throws NetworkErrorException {
            return null;
        }

        // Getting an authentication token is not supported
        @Override
        public Bundle getAuthToken(
                AccountAuthenticatorResponse r,
                Account account,
                String s,
                Bundle bundle) throws NetworkErrorException {
            throw new UnsupportedOperationException();
        }

        // Getting a label for the auth token is not supported
        @Override
        public String getAuthTokenLabel(String s) {
            throw new UnsupportedOperationException();
        }

        // Updating user credentials is not supported
        @Override
        public Bundle updateCredentials(
                AccountAuthenticatorResponse r,
                Account account,
                String s, Bundle bundle) throws NetworkErrorException {
            throw new UnsupportedOperationException();
        }

        // Checking features for the account is not supported
        @Override
        public Bundle hasFeatures(
                AccountAuthenticatorResponse r,
                Account account, String[] strings) throws NetworkErrorException {
            throw new UnsupportedOperationException();
        }

        @Override
        public Bundle getAccountRemovalAllowed(AccountAuthenticatorResponse response, Account account) throws NetworkErrorException {
            return super.getAccountRemovalAllowed(response, account);
        }
    }

public class AuthenticatorService extends Service {

    // Instance field that stores the authenticator object
    private Authenticator mAuthenticator;

    @Override
    public void onCreate() {
        // Create a new authenticator object
        mAuthenticator = new Authenticator(this);
    }

    /*
     * When the system binds to this Service to make the RPC call
     * return the authenticator's IBinder.
     */
    @Override
    public IBinder onBind(Intent intent) {
        return mAuthenticator.getIBinder();
    }
}

// Authenticator.xml 
// My App Package Name is "com.accountdemo"
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="com.google"
    android:icon="@drawable/abc_vector_test"
    android:label="@string/app_name"
    android:smallIcon="@drawable/abc_vector_test" />

// Added these lines in Manifest 
        <service android:name=".AuthenticatorService">
            <intent-filter>
                <action android:name="android.accounts.AccountAuthenticator" />
            </intent-filter>
            <meta-data
                android:name="android.accounts.AccountAuthenticator"
                android:resource="@xml/authenticator" />
        </service>

Я проверил этот код, используя системные ключи подписи платформы, но он все еще не работает. Пожалуйста, кто-нибудь, помогите мне решить проблему. Спасибо.

...