我发现解决方案是让应用程序ContentProvider
实现OnAccountsUpdateListener
。在其方法中附加ContentProvider
作为侦听器,然后实现接口方法,如onCreate
account_manager.addOnAccountsUpdatedListener(this, null, false)
@Override
public void onAccountsUpdated(final Account[] accounts) {
Ln.i("Accounts updated.");
final Iterable<String> account_list = new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private final Iterator<Account> account_list = Arrays.asList(accounts).iterator();
@Override
public boolean hasNext() {
return account_list.hasNext();
}
/** Extracts the next account name and wraps it in single quotes. */
@Override
public String next() {
return "'" + account_list.next().name + "'";
}
@Override
public void remove() { throw new UnsupportedOperationException("Not implemented"); }
};
}
};
final String account_set = TextUtils.join(", ", account_list);
Ln.i("Current accounts: %s", account_set);
// Removes content that is associated with accounts that are not currently connected
final SelectionBuilder builder = new SelectionBuilder();
builder.table(Tables.CALENDARS)
.where(Calendars.CALENDAR_USER + " NOT IN (?)", account_set);
new SafeAsyncTask() {
@Override
public Void call() throws Exception {
_model.openWritableDatabase();
_model.delete(builder);
return null;
}
}.execute();
getContext().getContentResolver().notifyChange(Calendars.NO_SYNC_URI, null, false);
}
我构建了一个String
当前连接的帐户,然后用它构建一个 SQL 查询String
。我在该查询的后台线程中对数据库执行删除操作,以删除与当前未连接的帐户关联的数据。我通知内容发生了变化,但不需要与服务器同步。