Sunday, February 5, 2012

Building an line-of-business Android app - Part 2

How to setup a custom account and a sync adapter for an Android application.


You can download this article's code from: http://ge.tt/9RZnuDD


This is what I'm talking about
Managing accounts

Most line-of-business applications will require a login and will use this to send and receive data from a server. We're going to create a small application that shows a requires the user to create a custom account in the phone, and will put a sync adapter in place to trigger the data sync.
Most of the code can be seen in Android's sync adapter sample. But at this point, I'll strip out all network I/O and just leave placeholders.

Authenticator activity


There is an activity that will be invoked when you go to your phone's account settings and you click "Add account". This activity must extend the AccountAuthenticatorActivity class.



package com.you.yourapp.sync;


import com.you.yourapp.Constants;
import com.you.yourapp.HomeActivity;
import com.you.yourapp.R;

import com.you.yourapp.network.NetworkUtility;


import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;


/**
 * Activity which displays login screen to the user.
 */
public class AuthenticatorActivity extends AccountAuthenticatorActivity {
public static final String PARAM_CONFIRMCREDENTIALS = "confirmCredentials";
public static final String PARAM_PASSWORD = "password";
public static final String PARAM_USERNAME = "username";
public static final String PARAM_AUTHTOKEN_TYPE = "authtokenType";


private static final String TAG = "AuthenticatorActivity";
public static final String START_APP_ON_SUCCESS_EXTRA = "START_APP_ON_SUCCESS";


private AccountManager mAccountManager;
private Thread mAuthThread;
private String mAuthtoken;
private String mAuthtokenType;


/**
* If set we are just checking that the user knows their credentials; this
* doesn't cause the user's password to be changed on the device.
*/
private Boolean mConfirmCredentials = false;


/** for posting authentication attempts back to UI thread */
private final Handler mHandler = new Handler();
private TextView mMessage;
private String mPassword;
private EditText mPasswordEdit;


/** Was the original caller asking for an entirely new account? */
protected boolean mRequestNewAccount = false;


private String mUsername;
private EditText mUsernameEdit;


/**
* {@inheritDoc}
*/
@Override
public void onCreate(Bundle icicle) {
Log.i(TAG, "onCreate(" + icicle + ")");
super.onCreate(icicle);
mAccountManager = AccountManager.get(this);
Log.i(TAG, "loading data from Intent");
final Intent intent = getIntent();
mUsername = intent.getStringExtra(PARAM_USERNAME);
mAuthtokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
mRequestNewAccount = mUsername == null;
mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS,
false);


Log.i(TAG, "    request new: " + mRequestNewAccount);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.login);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_dialog_alert);


mMessage = (TextView) findViewById(R.id.message);
mUsernameEdit = (EditText) findViewById(R.id.username_edit);
mPasswordEdit = (EditText) findViewById(R.id.password_edit);


mUsernameEdit.setText(mUsername);
mMessage.setText(getMessage());
}


/*
* {@inheritDoc}
*/
@Override
protected Dialog onCreateDialog(int id) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage(getText(R.string.login_activity_authenticating));
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Log.i(TAG, "dialog cancel has been invoked");
if (mAuthThread != null) {
mAuthThread.interrupt();
finish();
}
}
});
return dialog;
}


/**
* Handles onClick event on the Submit button. Sends username/password to
* the server for authentication.
* 
* @param view
*            The Submit button for which this method is invoked
*/
public void handleLogin(View view) {
if (mRequestNewAccount) {
mUsername = mUsernameEdit.getText().toString();
}
mPassword = mPasswordEdit.getText().toString();
if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
mMessage.setText(getMessage());
} else {
showProgress();
// Start authenticating...
mAuthThread = NetworkUtility.attemptAuth(mUsername, mPassword,
mHandler, AuthenticatorActivity.this);
}
}


/**
* Called when response is received from the server for confirm credentials
* request. See onAuthenticationResult(). Sets the
* AccountAuthenticatorResult which is sent back to the caller.
* 
* @param the
*            confirmCredentials result.
*/
protected void finishConfirmCredentials(boolean result) {
Log.i(TAG, "finishConfirmCredentials()");
final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
mAccountManager.setPassword(account, mPassword);
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}


/**
* 
* Called when response is received from the server for authentication
* request. See onAuthenticationResult(). Sets the
* AccountAuthenticatorResult which is sent back to the caller. Also sets
* the authToken in AccountManager for this account.
* 
* @param the
*            confirmCredentials result.
*/


protected void finishLogin() {
Log.i(TAG, "finishLogin()");
final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);


if (mRequestNewAccount) {
mAccountManager.addAccountExplicitly(account, mPassword, null);


// Trigger sync on content provider changes
ContentResolver.setSyncAutomatically(account,
Constants.SMALLB_AUTHORITY, true);


// Sync every 5 minutes
ContentResolver.addPeriodicSync(account,
Constants.SMALLB_AUTHORITY, new Bundle(), 300);
} else {
mAccountManager.setPassword(account, mPassword);
}


final Intent intent = new Intent();
mAuthtoken = mPassword;
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
if (mAuthtokenType != null
&& mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE)) {
intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);


if (getIntent().getBooleanExtra(START_APP_ON_SUCCESS_EXTRA, false)) {
startActivity(new Intent(getApplicationContext(),
HomeActivity.class));
}


finish();
}


/**
* Hides the progress UI for a lengthy operation.
*/
protected void hideProgress() {
dismissDialog(0);
}


/**
* Called when the authentication process completes (see attemptLogin()).
*/
public void onAuthenticationResult(boolean result) {
Log.i(TAG, "onAuthenticationResult(" + result + ")");
// Hide the progress dialog
hideProgress();
if (result) {
if (!mConfirmCredentials) {
finishLogin();
} else {
finishConfirmCredentials(true);
}
} else {
Log.e(TAG, "onAuthenticationResult: failed to authenticate");
if (mRequestNewAccount) {
mMessage.setText(getText(R.string.login_activity_loginfail_text_both));
} else {
mMessage.setText(getText(R.string.login_activity_loginfail_text_pwonly));
}
}
}


/**
* Returns the message to be displayed at the top of the login dialog box.
*/
private CharSequence getMessage() {
if (TextUtils.isEmpty(mUsername)) {
final CharSequence msg = getText(R.string.login_activity_newaccount_text);
return msg;
}
if (TextUtils.isEmpty(mPassword)) {
return getText(R.string.login_activity_loginfail_text_pwmissing);
}
return null;
}


/**
* Shows the progress UI for a lengthy operation.
*/
protected void showProgress() {
showDialog(0);
}
}

I highlighted a piece of code that checks if it was invoked with the START_APP_ON_SUCCESS_EXTRA flag set. This is because we will check in our home activity that if there's no account created, the user will be asked to create one. If this account creation succeeds the authenticator activity will re-launch our home activity.



Authenticator service


The authenticator service will be invoked by Android's account settings. Its key is to return the binder from an AbstractAccountAuthenticator class which we will add in a moment.


package com.you.yourapp.sync;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


/**
 * Service to handle Account authentication. It instantiates the authenticator
 * and returns its IBinder.
 */
public class AuthenticationService extends Service {
    private static final String TAG = "AuthenticationService";
    private Authenticator mAuthenticator;


    @Override
    public void onCreate() {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Authentication Service started.");
        }
        mAuthenticator = new Authenticator(this);
    }


    @Override
    public void onDestroy() {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Authentication Service stopped.");
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                "getBinder()...  returning the AccountAuthenticator binder for intent "
                    + intent);
        }
        return mAuthenticator.getIBinder();
    }
}

The authenticator class

The authenticator class must extend the AbstractAccountAuthenticator class, and it is responsible for handling the credentials check or token renewal for the Android's infrastructure.

package com.you.yourapp.sync;

import com.you.yourapp.Constants;
import com.you.yourapp.R;
import com.you.yourapp.network.NetworkUtility;

import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class Authenticator extends AbstractAccountAuthenticator {
// Authentication Service context
private final Context mContext;

public Authenticator(Context context) {
super(context);
mContext = context;
}

/**
* {@inheritDoc}
*/
@Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options) {
final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE,
authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}

/**
* {@inheritDoc}
*/
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response,
Account account, Bundle options) {
if (options != null && options.containsKey(AccountManager.KEY_PASSWORD)) {
final String password = options
.getString(AccountManager.KEY_PASSWORD);
final boolean verified = onlineConfirmPassword(account.name,
password);
final Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, verified);
return result;
}
// Launch AuthenticatorActivity to confirm credentials
final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
intent.putExtra(AuthenticatorActivity.PARAM_CONFIRMCREDENTIALS, true);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}

/**
* {@inheritDoc}
*/
@Override
public Bundle editProperties(AccountAuthenticatorResponse response,
String accountType) {
throw new UnsupportedOperationException();
}

/**
* {@inheritDoc}
*/
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle loginOptions) {
if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ERROR_MESSAGE,
"invalid authTokenType");
return result;
}
final AccountManager am = AccountManager.get(mContext);
final String password = am.getPassword(account);
if (password != null) {
final boolean verified = onlineConfirmPassword(account.name,
password);
if (verified) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE,
Constants.ACCOUNT_TYPE);
result.putString(AccountManager.KEY_AUTHTOKEN, password);
return result;
}
}
// the password was missing or incorrect, return an Intent to an
// Activity that will prompt the user for the password.
final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE,
authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}

/**
* {@inheritDoc}
*/
@Override
public String getAuthTokenLabel(String authTokenType) {
if (authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
return mContext.getString(R.string.app_name);
}
return null;
}

/**
* {@inheritDoc}
*/
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response,
Account account, String[] features) {
final Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
return result;
}

/**
* Validates user's password on the server
*/
private boolean onlineConfirmPassword(String username, String password) {
return NetworkUtility.authenticate(username, password, null, null);
}

/**
* {@inheritDoc}
*/
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle loginOptions) {
final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE,
authTokenType);
intent.putExtra(AuthenticatorActivity.PARAM_CONFIRMCREDENTIALS, false);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}

}

The highlighted code invokes a NetworkUtility class which will make the network calls to authenticate the user. This class goes as follows, and I have hard-coded that only "user" and "pass" will authenticate, as we still have no server code.

package com.you.yourapp.network;

import android.content.Context;
import android.os.Handler;

import com.you.yourapp.sync.AuthenticatorActivity;

/**
 * Provides utility methods for communicating with the server.
 */
public class NetworkUtility {
/**
* Executes the network requests on a separate thread.
* 
* @param runnable
*            The runnable instance containing network mOperations to be
*            executed.
*/
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {

}
}
};
t.start();
return t;
}

/**
* Connects to the server, authenticates the provided username and password.
* 
* @param username
*            The user's username
* @param password
*            The user's password
* @param handler
*            The hander instance from the calling UI thread.
* @param context
*            The context of the calling Activity.
* @return boolean The boolean result indicating whether the user was
*         successfully authenticated.
*/
public static boolean authenticate(String username, String password,
Handler handler, final Context context) {
boolean isValid = authenticate(username, password);

sendResult(isValid, handler, context);
return isValid;
}
/**
* Connects to the server, authenticates the provided username and password.
* 
* @param username
*            The user's username
* @param password
*            The user's password
* @return boolean The boolean result indicating whether the user was
*         successfully authenticated.
*/
public static boolean authenticate(String username, String password) {
return username != null && username.equals("user") && password != null
&& password.equals("pass");
}

/**
* Sends the authentication response from server back to the caller main UI
* thread through its handler.
* 
* @param result
*            The boolean holding authentication result
* @param handler
*            The main UI thread's handler instance.
* @param context
*            The caller Activity's context.
*/
private static void sendResult(final Boolean result, final Handler handler,
final Context context) {
if (handler == null || context == null) {
return;
}
handler.post(new Runnable() {
public void run() {
((AuthenticatorActivity) context)
.onAuthenticationResult(result);
}
});
}

/**
* Attempts to authenticate the user credentials on the server.
* 
* @param username
*            The user's username
* @param password
*            The user's password to be authenticated
* @param handler
*            The main UI thread's handler instance.
* @param context
*            The caller Activity's context
* @return Thread The thread on which the network mOperations are executed.
*/
public static Thread attemptAuth(final String username,
final String password, final Handler handler, final Context context) {
final Runnable runnable = new Runnable() {
public void run() {
authenticate(username, password, handler, context);
}
};
return NetworkUtility.performOnBackgroundThread(runnable);
}
}


Sync adapter

Our sync adapter will do nothing at this time, just run, but in the next part of this tutorial we'll add the server side code and we will be trafficking JSON bits:


package com.you.yourapp.sync;


import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;


public class YourAppSyncAdapter extends AbstractThreadedSyncAdapter {
public YourAppSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}


private static final String LOG_TAG = "YourApp-SyncAdapter";
public static boolean isSyncing;


@Override
public void onPerformSync(final Account account, Bundle extras,
String authority, ContentProviderClient provider,
SyncResult syncResult) {
new Thread() {
public void run() {
Log.i(LOG_TAG, "Started sync");


if (isSyncing) {
return;
}


isSyncing = true;


try {
// ... sync here
} finally {
isSyncing = false;
}
}
}.start();
}
}


Sync adapter service

The sync adapter is simple, and exists because of the same reason as the AuthenticatorService, to provide Android's framework with a specific binder contract for the background sync.


package com.you.yourapp.sync;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;


public class YourAppSyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static YourAppSyncAdapter sSyncAdapter = null;


/*
* {@inheritDoc}
*/
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new YourAppSyncAdapter(getApplicationContext(), true);
}
}
}


/*
* {@inheritDoc}
*/
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}



Layout files and strings


This is the missing res/layout/login.xml file that will pop up when entering our credentials:



<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="5dip"
            android:paddingBottom="13dip"
            android:paddingLeft="20dip"
            android:paddingRight="20dip">
            <TextView
                android:id="@+id/message"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dip" />
            <TextView
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textStyle="bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_activity_username_label" />
            <EditText
                android:id="@+id/username_edit"
                android:singleLine="true"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minWidth="250dip"
                android:scrollHorizontally="true"
                android:capitalize="none"
                android:autoText="false"
                android:inputType="textEmailAddress" />
            <TextView
                android:id="@+id/username_fixed"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:singleLine="true"
                android:layout_marginTop="2dip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TextView
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textStyle="bold"
                android:singleLine="true"
                android:layout_marginTop="2dip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_activity_password_label" />
            <EditText
                android:id="@+id/password_edit"
                android:singleLine="true"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minWidth="250dip"
                android:scrollHorizontally="true"
                android:capitalize="none"
                android:autoText="false"
                android:password="true"
                android:inputType="textPassword" />
            <TextView
                android:id="@+id/message_bottom"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dip" />
        </LinearLayout>
    </ScrollView>
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#c6c3c6"
        android:minHeight="54dip"
        android:paddingTop="4dip"
        android:paddingLeft="2dip"
        android:paddingRight="2dip">
        <Button
            android:id="@+id/ok_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:minWidth="100dip"
            android:text="@string/login_activity_ok_button"
            android:onClick="handleLogin" />
    </FrameLayout>
</LinearLayout>

And these are the strings we will add to our res/values/strings.xml file:

<string name="login_activity_username_label">User:</string>
<string name="login_activity_password_label">Password:</string>
<string name="login_activity_ok_button">Sign in</string>
<string name="login_activity_authenticating">Authenticating\u2026</string>
<string name="login_activity_newaccount_text">Sign in with your YourApp account.</string>
<string name="login_activity_loginfail_text_pwmissing">Enter your account password.</string>
<string name="login_activity_loginfail_text_pwonly">Please, enter your password again. It was wrong or account has changed.</string>
<string name="login_activity_loginfail_text_both">Enter a valid YourApp account.</string>
<string name="login_activity_title">Sign-in</string>

Asking the user to create an account on startup


We will place the following piece of code at the top of our HomeActivity onCreate method:


super.onCreate(savedInstanceState);


if (AccountManager.get(this).getAccountsByType(Constants.ACCOUNT_TYPE).length == 0) {
Intent intent = new Intent(getApplicationContext(),
AuthenticatorActivity.class);
intent.putExtra(AuthenticatorActivity.START_APP_ON_SUCCESS_EXTRA,
true);


startActivity(intent);
finish();
}


Constants class

Different pieces of code references this constants. Please remember that this is not the only place where this strings appear, they also appear in authenticator.xml, syncadapter.xml and AndroidManifest.xml.


package com.you.yourapp;


public class Constants {
private Constants(){
}

public static final String PREF_NAME = "YourApp";
public static final String AUTHTOKEN_TYPE = "com.you.yourapp";
public static final String ACCOUNT_TYPE = "com.you.yourapp";
public static final String SMALLB_AUTHORITY = "com.you.yourapp";
}



Android's manifest


Add the following XML fragment to your manifest inside the application tag:

<activity
    android:name=".sync.AuthenticatorActivity"
    android:configChanges="orientation"
    android:excludeFromRecents="true"
    android:label="@string/ui_activity_title"
    android:theme="@android:style/Theme.Dialog" />


<service
    android:name=".sync.AuthenticationService"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.accounts.AccountAuthenticator" />
    </intent-filter>


    <meta-data
        android:name="android.accounts.AccountAuthenticator"
        android:resource="@xml/authenticator" />
</service>
<service
    android:name=".sync.YourAppSyncService"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.content.SyncAdapter" />
    </intent-filter>


    <meta-data
        android:name="android.content.SyncAdapter"
        android:resource="@xml/yourapp_syncadapter" />
</service>


<provider
    android:name=".providers.YourAppContentProvider"
    android:authorities="com.you.yourapp"
    android:label="@string/yourapp_provider_label" >
</provider>

Above, I highlighted three fragments:

@xml/authenticator: The content of this XML file, placed in res/xml/authenticator.xml looks like this:

<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="com.you.yourapp"
    android:icon="@drawable/ic_launcher"
    android:smallIcon="@drawable/ic_launcher"
    android:label="@string/label"
/>

@xml/yourapp_syncadapter: The content of this XML file, placed in res/xml/authenticator.xml looks like this:

<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
    android:contentAuthority="com.you.yourapp"
    android:accountType="com.you.yourapp"
    android:userVisible="true"
    android:supportsUploading="false"
/>

com.you.yourapp: This is the application's content provider authority that this sync adapter will handle. Please note that if you set your sync adapter to sync automatically, what Android does is to monitor for write operations in your content providers. Be careful, as you probably don't want to make a network request each time this occur.

And now, add the permission requirements, these goes outside the application tag of your manifest file:



<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

Hope you find this post useful,

1 comment:

  1. And for those who want to try improving this on your own, here is a little tip:

    I use Google App Engine as server backend. The easiest way to work with both Android and App Engine at the same time is to use Android's emulator and run the backend using the development web server in the same machine. You can target emulator's host machine using the 10.0.2.2 IP address. Using the --address=0.0.0.0 flag when running the App Engine emulator allows the emulator to reach the development server. Then, I simply point my Android client to http://10.0.2.2:8888/ (if the backend listents that port) to test the client-server interaction.

    ReplyDelete