如何以编程方式添加自定义帐户的Andr​​oid? [英] How to add programmatically a custom account in android?

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

问题描述

我想创建我希望我的账户是在的设置也账户部分看到我的应用程序,在那里我可以有我的联系方式对我的帐户,如Facebook,Viber的,WhatsApp的等账户。有任何想法吗?我用Google搜索了很多,但找不到正确的答案在哪里开始。请帮忙。 我曾尝试创建一个帐户是如下。这使我的错误。

 帐户的帐户=新帐户(标题,com.package.nom);
               字符串password =密码;

               的AccountManager的AccountManager =
                       (的AccountManager)MainPanel.this.getSystemService(
                               ACCOUNT_SERVICE);
               accountManager.addAccountExplicitly(账号,密码为空);
 

解决方案

您需要安装多个组件,能够以编程方式创建一个帐户。您需要:

  • 的AccountAuthenticator
  • 服务提供访问AccountAuthenticator
  • 在一些权限

的身份验证

该认证是一个对象,这将使帐户类型和autority(即Linux的用户)有权利之间的映射来管理它。

声明的身份验证在XML中完成:

  • 创建一个文件 RES / XML / authenticator.xml

包含以下内容:

 < XML版本=1.0编码=UTF-8&GT?;
<账户身份验证的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
                   机器人:accountType =com.company.demo.account.DEMOACCOUNT
                   机器人:图标=@可绘制/ ic_launcher
                   机器人:smallIcon =@可绘制/ ic_launcher
                   机器人:标签=@字符串/ my_custom_account/>
 

请注意了accountType:它必须在code被重用,当您创建的帐户。 图标和标签将使用设置应用程序,以显示该类型的帐户。

实施AccountAuthenticator

您必须延伸 AbstractAccountAuthenticator 做到这一点。这将是使用第三方应用程序来访问帐户数据。

下面的示例不允许任何访问第三方应用程序,所以每个方法的实现实在是微不足道。

 公共类CustomAuthenticator扩展AbstractAccountAuthenticator {

    公共CustomAuthenticator(上下文的背景下){
        超(上下文);
    }

    @覆盖
    公共捆绑addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse,字符串S,S2的字符串,字符串[]字符串,束束)抛出NetworkErrorException {
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共捆绑editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse,String s)将{
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共捆绑confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse,帐帐,束束)抛出NetworkErrorException {
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共捆绑getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse,帐帐,的String,束束)抛出NetworkErrorException {
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共字符串getAuthTokenLabel(String s)将{
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共捆绑updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse,帐帐,的String,束束)抛出NetworkErrorException {
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }

    @覆盖
    公共捆绑hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse,帐帐,字符串[]字符串)抛出NetworkErrorException {
        返回null; //要改变的实现方法正文中使用文件|设置|文件模板。
    }
}
 

的服务暴露出帐户类型

创建服务来操作该类型的账户:

 公共类AuthenticatorService延伸服务{
    @覆盖
    公众的IBinder onBind(意向意图){
        CustomAuthenticator身份验证=新CustomAuthenticator(本);
        返回authenticator.getIBinder();
    }
}
 

在声明服务您的清单

 <服务机器人:名称=com.company.demo.account.AuthenticatorService机器人:出口=假>
        <意向滤光器>
            <作用机器人:名称=android.accounts.AccountAuthenticator/>
        &所述; /意图滤光器>
        &所述;元数据
            机器人:名称=android.accounts.AccountAuthenticator
            机器人:资源=@ XML /身份验证/>
    < /服务>
 

下面,在过滤器和元数据参照的XML资源宣告认证器的关键点是

的权限

在你的清单一定要申报下列权限

 <使用-权限的Andr​​oid:名称=android.permission.AUTHENTICATE_ACCOUNTS/>
<使用-权限的Andr​​oid:名称=android.permission.GET_ACCOUNTS/>
<使用-权限的Andr​​oid:名称=android.permission.MANAGE_ACCOUNTS/>
 

(不是所有的需要psented在这个岗位样品code $ P $,但你可能会有一些code有关账户管理,并在年底他们都将是有益的)

创建于code帐户

现在是万事俱备,你创建具有以下code的账户。注意布尔 addAccountExplicitly 返回通知您的成功或失败。

 的AccountManager的AccountManager = AccountManager.get(本); //这是活动
    账户账户=新帐户(我的帐户,com.company.demo.account.DEMOACCOUNT);
    布尔成功= accountManager.addAccountExplicitly(帐户,密码,NULL);
    如果(成功){
        Log.d(TAG,创建帐户);
    }其他{
        Log.d(TAG,帐户创建失败,看previous日志进行调查。);
    }
 

最后提示

不要在外部存储安装的应用程序

如果您的应用程序安装在外接存储,也有很好的机会,Android的删除你的账户数据时,SD卡卸载(因为身份验证该帐户将无法访问了)。因此,为了避免这种损失(在每次系统启动!),您必须安装应用程序,宣布对内部存储认证只有:

 <舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
      机器人:INSTALLLOCATION =internalOnly
      ...
 

如果出现问题,

阅读日志仔细,该AccountManger是许多允许输出日志,以帮助您调试code。

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:

  • an AccountAuthenticator
  • a Service to provide access to the AccountAuthenticator
  • some permissions

The authenticator

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.

Declaring an authenticator is done in xml :

  • create a file res/xml/authenticator.xml

with the following content :

<?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"/>

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.

Implementing the AccountAuthenticator

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

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

The Service exposing the Account Type

Create a Service to manipulate the Accounts of that type :

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

Declare the service in your manifest :

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

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

The permissions

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)

Create an account in code

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");
    }

Final tips

Don't install your app on external storage

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

In case of trouble

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆