이전에 Authenticator Service 를 구현해 보았습니다.

이제 이것을 이용하는 SyncAdapter 를 구현해 보도록 하겠습니다.

 

SyncAdapter 는 구글 싱크가 일어날때 자동으로 싱크를 처리해주는 부분으로서

“Accounts & Sync” 셋팅메뉴에서 원하는 아이디를 클릭하면 SyncAdapter 의 리스트를 확인할 수 있습니다.

 

그럼 먼저 “Accounts & Sync” 메뉴에서 “Add account” 버튼을 눌러 이전에 만들었던 계정으로 로그인을 합니다.

 

image

 

위와 같이 로그인된 아이디가 저장이 될텐데 저 아이디를 클릭하면 이 계정에 등록되어진 SyncAdapter 를 확인할 수 있습니다.

현재에는 하나도 없는것을 볼 수 있는데 이번 포스트에서 여기에 추가해보도록 하겠습니다.

 

SyncAdapter 는 Service 로 이루어져 있습니다.

 

Service 를 추가하기전에 SyncAdapter 를 쓰기 위한 권한을 추가합니다.

아래 내용을 manifest 에 등록합니다.

 

<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />  
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

이제 아래와 같은 형태의 서비스를 추가합니다.

<service android:name=".syncadapter.SyncService">
<intent-filter>
<action
android:name="android.content.SyncAdapter"
/>
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/syncadapter" />
</service>

그다음 syncadapter.xml 파일을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>

<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.android.contacts"
android:accountType="net.cranix.android.cranixsyncsample"
android:supportsUploading="false"
/>

“android:contentAuthority” 는 sync 할 ContentProvider 를 지정합니다.

여기서 Sync 이름은 우리가 직접 지정하는 것이 아니고 이 ContentProvider 의 이름을 따라가기 때문에 유의해야 합니다.

 

“android:supportsUploading” 은 폰에서 이 SyncAdapter 의 데이터를 변경 가능한게 할지 말지를 결정하는 것 입니다.

이것을 false 로 하면 서버에서 싱크만 되고 폰에서는 수정이안되는 readonly 상태가 됩니다.

 

이제 마지막으로 SyncService 와 SyncAdapter 소스를 구현해 보도록 합니다.

먼저 SyncService 입니다.

package net.cranix.android.cranixsyncsample.syncadapter;

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

public class SyncService extends Service {
private SyncAdapter syncAdapter;

@Override
public void onCreate() {
super.onCreate();
syncAdapter = new SyncAdapter(this,true);
}
@Override
public IBinder onBind(Intent arg0) {
return syncAdapter.getSyncAdapterBinder();
}

}


이 Service 는 SyncAdapter 에 모든 처리를 위임합니다.

SyncAdapter 를 보면 다음과 같습니다.

package net.cranix.android.cranixsyncsample.syncadapter;



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

public class SyncAdapter extends AbstractThreadedSyncAdapter {



public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}

@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {

// TODO : Sync 처리
}
}

 

이제 “Accounts & sync” 메뉴에서 아이디를 클릭해 보면 아래와 같이 추가된 SyncAdapter 가 보일 것입니다.

image

 

 

이제 위의 “Sync Contacts” 를 클릭하거나 시스템에서 sync 가 발생할때 위 SyncAdapter 의 onPerformSync 메소드가 호출되게 됩니다.

결국 실제 Sync 를 처리하는 구문은 onPerformSync 메소드만 구현해주면 됩니다.

by cranix 2010. 12. 27. 14:08