是否可以在Android应用中仅同步电话簿中新插入的联系人?假设我第一次将我的电话簿与应用程序同步并保存这些联系人。当我需要显示这些联系人时,只有新插入的联系人才会同步,而其他联系人只能从数据库中检索。
答案 0 :(得分:1)
public class ContactListenerService extends Service {
MyContentObserver contentObserver = new MyContentObserver();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
getApplicationContext().getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contentObserver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean flag = PreferencesManager.getInstance(this).optBoolean("flag");
if(flag==false){
Toast.makeText(this, flag+" val", Toast.LENGTH_LONG).show();
}else{
PreferencesManager.getInstance(getApplicationContext()).putBoolean("flag",false);
// your method to sync contact
}
return Service.START_STICKY;
}
private class MyContentObserver extends ContentObserver {
boolean flag=false;
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
PreferencesManager.getInstance(getApplicationContext()).putBoolean("flag",true);
super.onChange(selfChange);
}
@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
}
}
public class ContactSyncScreen extends BaseFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Your other stuff
//Start the service form fragment
Intent intent=new Intent(getActivity(),ContactListenerService.class);
getActivity().startService(intent);
}
}