- Sync Adapter Class を作る
- Service をバインドする
- Sync adapter XML metadata file を準備する
- AndroidManifest.xml への宣言
Sync Adapter Classを作る
AbstractThreadedSyncAdapterの拡張
コンストラクタの作成
/**
* Handle the transfer of data between a server and an
* app, using the Android sync adapter framework.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
...
// Global variables
// Define a variable to contain a content resolver instance
ContentResolver mContentResolver; // 情報を操作するオブジェクト
...
/* Sync Adapter の設定 */
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
/*
* If your app uses a content resolver, get an instance of it
* from the incoming Context
*/
mContentResolver = context.getContentResolver();
}
...
/**
* Set up the sync adapter. This form of the
* constructor maintains compatibility with Android 3.0
* and later platform versions
*/
public SyncAdapter(
Context context,
boolean autoInitialize,
boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
/*
* If your app uses a content resolver, get an instance of it
* from the incoming Context
*/
mContentResolver = context.getContentResolver();
...
}
データの通信 : onPerformSync() 内で実施。
引数は簡単に呼び出せるように、
- (Account) account
- (Bundle) Extras
- (String) Authority
- (ContentProviderClient)
- (SyncResult)syncresult
実装する機能。以下を読むと、何だ、全部人でやるんじゃん、って思った。でも、以下の処理をバックグラウンドでやってくれる。
- サーバに接続
- Sync Adapter がネットワークにつないでくれるわけじゃない
- データのダウンロード、アップロード
- ダウンロード、アップロードを勝手にはやってくれないので、自分で実装する。
- ネットワークエラーの処理も自分で取り扱う必要あり
- Handling data conflicts or determining how current the data is
- サーバでデータのコンフリクトが起こっても、やっぱり自分で対処。
- ネットワークを閉じるなどの終了処理
ContentResolverなんかでデータを挿入したりするのはここで書くのか。
Sync Adapter をサービスにバインドする
- Serviceの中のonCreate()にてSync Adapter コンポーネント生成する。
- thread-safeで作る
package com.example.android.syncadapter;
/**
* Define a Service that returns an IBinder for the
* sync adapter class, allowing the sync adapter framework to call
* onPerformSync().
*/
public class SyncService extends Service {
// Storage for an instance of the sync adapter
private static SyncAdapter sSyncAdapter = null;
// Object to use as a thread-safe lock
private static final Object sSyncAdapterLock = new Object();
/*
* Instantiate the sync adapter object.
*/
@Override
public void onCreate() {
/*
* Create the sync adapter as a singleton.
* Set the sync adapter as syncable
* Disallow parallel syncs
*/
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
/**
* Return an object that allows the system to invoke
* the sync adapter.
*
*/
@Override
public IBinder onBind(Intent intent) {
/*
* Get the object that allows external processes
* to call onPerformSync(). The object is created
* in the base class code when the SyncAdapter
* constructors call super()
*/
return sSyncAdapter.getSyncAdapterBinder();
}
}
最終更新:2013年11月12日 00:19