如何以编程方式在android中添加自定义帐户?

How to add programmatically a custom account in android?(如何以编程方式在android中添加自定义帐户?)

本文介绍了如何以编程方式在android中添加自定义帐户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序创建一个帐户,在那里我可以将我的联系人与我的帐户联系起来,例如 facebook、viber、whatsapp 等.我希望我的帐户也可以在设置的帐户部分中显示.有任何想法吗?我用谷歌搜索了很多,但找不到正确的答案从哪里开始.请帮忙.我尝试创建的帐户如下.这导致我出错.

I am trying to create an account for my app, where I will be able to have my contacts against my account like facebook, viber, whatsapp etc. I want my account to be visible in the account section of the settings also. Any ideas? I have googled a lot, but couldn't find a right answer where to start. Please help. What I have tried to create an account is as below. Which leads me to an error.

Account account = new Account("Title", "com.package.nom");
               String password = "password";

               AccountManager accountManager =
                       (AccountManager) MainPanel.this.getSystemService(
                               ACCOUNT_SERVICE);
               accountManager.addAccountExplicitly(account, password, null);

推荐答案

您需要设置多个组件才能以编程方式创建帐户.你需要:

You need to setup multiple components to be able to create an account programmatically. You need:

  • 账户验证器
  • 提供对 AccountAuthenticator 的访问权限的服务
  • 一些权限

身份验证器是一个对象,它将在帐户类型和有权管理它的权限(即 linux 用户)之间进行映射.

The authenticator is an object that will make the mapping between the account type and the autority (i.e. the linux-user) that have rights to manage it.

声明身份验证器在 xml 中完成:

  • 创建一个文件res/xml/authenticator.xml

内容如下:

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

注意 accountType :当您创建帐户时,它必须在代码中重用.设置"应用将使用图标和标签来显示该类型的帐户.

Note the accountType : it must be reused in code when you create the Account. The icons and label will be used by the "Settings" app to display the accounts of that type.

实现 AccountAuthenticator

您必须扩展 AbstractAccountAuthenticator 才能做到这一点.这将被第三方应用用于访问帐户数据.

You must extends AbstractAccountAuthenticator to do that. This will be use by third party app to access Account data.

以下示例不允许对 3rd-party 应用程序进行任何访问,因此每个方法的实现都很简单.

The following sample don't allow any access to 3rd-party app and so the implementation of each method is trivial.

public class CustomAuthenticator extends AbstractAccountAuthenticator {

    public CustomAuthenticator(Context context) {
        super(context);
    }

    @Override
    public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse, String s, String s2, String[] strings, Bundle bundle) throws NetworkErrorException {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String s) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle bundle) throws NetworkErrorException {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public String getAuthTokenLabel(String s) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] strings) throws NetworkErrorException {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}

暴露账户类型的服务

创建一个服务来操作该类型的帐户:

public class AuthenticatorService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        CustomAuthenticator authenticator = new CustomAuthenticator(this);
        return authenticator.getIBinder();
    }
}

在清单中声明服务:

<service android:name="com.company.demo.account.AuthenticatorService" android:exported="false">
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator"/>
        </intent-filter>
        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator"/>
    </service>

这里,过滤器和引用声明身份验证器的xml资源的元数据是关键.

Here, the filter and the meta-data referring to the xml resource declaring the authenticator are the key points.

请务必在您的清单中声明以下权限

In your manifest be sure to declare the following permissions

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

(本文中的示例代码并非全部都需要,但您可能会有更多关于帐户管理的代码,最后它们都会很有用)

(not all required for the sample code presented in this post, but you will probably have some more code about account management and at the end all of them will be useful)

现在一切准备就绪,您可以使用以下代码创建一个帐户.注意 addAccountExplicitly 返回的 boolean 通知您成功或失败.

Now that everything is ready you create an account with the following code. Note the boolean returned by addAccountExplicitly informing you about the success or failure.

    AccountManager accountManager = AccountManager.get(this); //this is Activity
    Account account = new Account("MyAccount","com.company.demo.account.DEMOACCOUNT");
    boolean success = accountManager.addAccountExplicitly(account,"password",null);
    if(success){
        Log.d(TAG,"Account created");
    }else{
        Log.d(TAG,"Account creation failed. Look at previous logs to investigate");
    }

最后提示

不要将您的应用安装在外部存储设备上

如果您的应用安装在外部存储上,Android 很有可能会在卸载 sdcard 时删除您的帐户数据(因为该帐户的身份验证器将无法再访问).因此,为了避免这种损失(每次重新启动!!!),您必须安装应用程序,仅在内部存储上声明身份验证器:

If your app is installed on external storage, there are good chance that Android delete your Account data when sdcard is unmounted (since the authenticator for that account will not be accessible anymore). So to avoid this loss (on every reboot !!!) you must install the App declaring the authenticator on internal storage only :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:installLocation="internalOnly"
      ...

遇到问题时

仔细阅读日志,AccountManger 正在输出许多日志以帮助您调试代码.

Read the logs carefully, The AccountManger is outputing many logs to help you to debug your code.

这篇关于如何以编程方式在android中添加自定义帐户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何以编程方式在android中添加自定义帐户?

基础教程推荐