下面列出了android.content.ContentResolver#setIsSyncable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void removeAccount(final Account account) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().remove("queueName").apply();
ContentResolver.setIsSyncable(account, WEBINSTALL_SYNC_AUTHORITY, 0);
ContentResolver.setSyncAutomatically(account, MyAccountActivity.WEBINSTALL_SYNC_AUTHORITY, false);
if(Build.VERSION.SDK_INT>=8){
ContentResolver.removePeriodicSync(account, MyAccountActivity.WEBINSTALL_SYNC_AUTHORITY, new Bundle());
}
mAccountManager.removeAccount(account, new AccountManagerCallback<Boolean>() {
@Override
public void run(AccountManagerFuture<Boolean> future) {
addAccount();
finish();
}
}, null);
}
public static void setUpPeriodicSync(Context context, String inputId) {
inputId = inputId==null?"":inputId;
Account account = DummyAccountService.getAccount(context);
AccountManager accountManager =
(AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
if (!accountManager.addAccountExplicitly(account, null, null)) {
Log.w(TAG, "Account already exists.");
// return;
}
Log.d(TAG, "Set sync with "+inputId);
ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
Bundle bundle = new Bundle();
bundle.putString(SyncAdapter.BUNDLE_KEY_INPUT_ID, inputId);
ContentResolver.addPeriodicSync(account, CONTENT_AUTHORITY, bundle,
SyncAdapter.SYNC_FREQUENCY_SEC/6); //Sync every hour b/c why not?
}
/**
* Add account for Birthday Adapter to Android system
*/
public Bundle addAccountAndSync() {
Log.d(getClass().getSimpleName(), "Adding calendar account : " + account.name);
// enable automatic sync once per day
ContentResolver.setSyncAutomatically(account, authority, true);
ContentResolver.setIsSyncable(account, type, 1);
// add periodic sync interval once per day
long freq = AlarmManager.INTERVAL_DAY;
ContentResolver.addPeriodicSync(account, type, new Bundle(), freq);
AccountManager accountManager = AccountManager.get(context);
if (accountManager.addAccountExplicitly(account, null, null)) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
// Force a sync! Even when background sync is disabled, this will force one sync!
manualSync();
return result;
} else {
return null;
}
}
public boolean requestSync(boolean onlyCheckins) {
if (!isUserLoggedIn()) {
return false;
}
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
extras.putString(SyncAdapter.EXTRA_AUTH_TOKEN, mAuthToken);
extras.putBoolean(SyncAdapter.EXTRA_ONLY_CHECKINS, onlyCheckins);
ContentResolver.setSyncAutomatically(mAccount, Table.AUTHORITY, true);
ContentResolver.setIsSyncable(mAccount, Table.AUTHORITY, 1);
if (ContentResolver.isSyncPending(mAccount, Table.AUTHORITY) ||
ContentResolver.isSyncActive(mAccount, Table.AUTHORITY)) {
ContentResolver.cancelSync(mAccount, Table.AUTHORITY);
}
ContentResolver.requestSync(mAccount, Table.AUTHORITY, extras);
return true;
}
public static void setupAccount(Context context) {
AccountManager manager = AccountManager.get(context);
Account account = getAccount(context);
try {
if (manager.addAccountExplicitly(account, null, null)) {
ContentResolver.setIsSyncable(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, 1);
ContentResolver.setSyncAutomatically(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, true);
ContentResolver.addPeriodicSync(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, new Bundle(),
12 * 60 * 60 /* 12 hours in seconds */);
}
} catch (SecurityException e) {
Timber.e(e, "Unable to add account");
}
}
private static Optional<AccountHolder> createAccount(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account account = new Account(context.getString(R.string.app_name), context.getPackageName());
if (accountManager.addAccountExplicitly(account, null, null)) {
Log.i(TAG, "Created new account...");
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
return Optional.of(new AccountHolder(account, true));
} else {
Log.w(TAG, "Failed to create account!");
return Optional.absent();
}
}
public static void initializePeriodicSync(Context context, long syncIntervalInSeconds) {
// Enable Sync
ContentResolver.setIsSyncable(PredatorAccount.getAccount(context),
Constants.Authenticator.PREDATOR_ACCOUNT_TYPE,
Constants.Sync.ON);
// Set periodic sync interval
Logger.d(TAG, "initializePeriodicSync: interval(seconds): " + syncIntervalInSeconds);
ContentResolver.addPeriodicSync(
PredatorAccount.getAccount(context),
Constants.Authenticator.PREDATOR_ACCOUNT_TYPE,
Bundle.EMPTY,
syncIntervalInSeconds);
}
public static void removePeriodicSync(Context context) {
// Disable Sync
ContentResolver.setIsSyncable(PredatorAccount.getAccount(context),
Constants.Authenticator.PREDATOR_ACCOUNT_TYPE,
Constants.Sync.OFF);
Logger.d(TAG, "removePeriodicSync: true");
ContentResolver.removePeriodicSync(
PredatorAccount.getAccount(context),
Constants.Authenticator.PREDATOR_ACCOUNT_TYPE,
Bundle.EMPTY);
}
public void setSyncPeriodic(String authority, long interval_in_minute,
long seconds_per_minute, long milliseconds_per_second) {
Account account = mUser.getAccount();
Bundle extras = new Bundle();
this.setAutoSync(authority, true);
ContentResolver.setIsSyncable(account, authority, 1);
final long sync_interval = interval_in_minute * seconds_per_minute
* milliseconds_per_second;
ContentResolver.addPeriodicSync(account, authority, extras,
sync_interval);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
((TextView) this.accountSpinner.getSelectedView()).setBackgroundColor(0xFFB6B6B6);
Account account = Listactivity.accounts[pos];
// Check periodic sync. If set to 86400 (once a day), set it to 900 (15 minutes)
// this is due to bad upgrade to v4 which handles offline mode and syncing
// Remove this code after V4.0 if version no more used
List<PeriodicSync> currentSyncs = ContentResolver.getPeriodicSyncs (account, AUTHORITY);
for (PeriodicSync onesync : currentSyncs) {
if (onesync.period == 86400) {
ContentResolver.setIsSyncable(account, AUTHORITY, 1);
ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 60);
Toast.makeText(getApplicationContext(), "Recreating this account is recommended to manage sync interval. Set to 15 minutes in the meantime",
Toast.LENGTH_LONG).show();
}
}
// End of code
Listactivity.imapNotes2Account.SetAccountname(account.name);
Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData (account, "username"));
String pwd = Listactivity.accountManager.getPassword(account);
Listactivity.imapNotes2Account.SetPassword(pwd);
Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData (account, "server"));
Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData (account, "portnum"));
Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData (account, "security"));
Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData (account, "usesticky"));
Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData (account, "syncinterval"));
Listactivity.imapNotes2Account.SetaccountHasChanged();
Listactivity.imapNotes2Account.SetAccount(account);
this.RefreshList();
}
/**
* Create an entry for this application in the system account list, if it isn't already there.
*
* @param context Context
*/
@TargetApi(Build.VERSION_CODES.FROYO)
public static void CreateSyncAccount(Context context) {
boolean newAccount = false;
boolean setupComplete = PreferenceManager
.getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);
// Create account, if it's missing. (Either first run, or user has deleted account.)
Account account = GenericAccountService.GetAccount(ACCOUNT_TYPE);
AccountManager accountManager =
(AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
if (accountManager.addAccountExplicitly(account, null, null)) {
// Inform the system that this account supports sync
ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
// Inform the system that this account is eligible for auto sync when the network is up
ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
// Recommend a schedule for automatic synchronization. The system may modify this based
// on other scheduled syncs and network utilization.
ContentResolver.addPeriodicSync(
account, CONTENT_AUTHORITY, new Bundle(),SYNC_FREQUENCY);
newAccount = true;
}
// Schedule an initial sync if we detect problems with either our account or our local
// data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
// the account list, so wee need to check both.)
if (newAccount || !setupComplete) {
TriggerRefresh();
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putBoolean(PREF_SETUP_COMPLETE, true).commit();
}
}
@Override
public void setIsSyncable(Account account, String authority, int syncable) {
ContentResolver.setIsSyncable(account, authority, syncable);
}
private void enableSync() {
Account acc = User.getAccount();
ContentResolver.setIsSyncable(acc, Contract.AUTHORITY, 1);
ContentResolver.setSyncAutomatically(acc, Contract.AUTHORITY, true);
ContentResolver.removePeriodicSync(acc, Contract.AUTHORITY, Bundle.EMPTY);
long interval = Settings.getAutoSyncInterval();
if (interval > 0) {
ContentResolver.addPeriodicSync(acc, Contract.AUTHORITY, Bundle.EMPTY, interval);
}
Bundle b = new Bundle();
b.putBoolean("resync_files", true);
SyncHelper.requestManualSync(acc, b);
Toast.makeText(GlobalApplication.getAppContext(), GlobalApplication.getAppContext().getString(R.string.data_resyncing), Toast.LENGTH_SHORT).show();
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE)) {
Account signedInAccount = ChromeSigninController.get(getContext()).getSignedInUser();
if (account.equals(signedInAccount)) {
ContentResolver.setIsSyncable(account, authority, 1);
} else {
ContentResolver.setIsSyncable(account, authority, 0);
}
return;
}
PendingInvalidation invalidation = new PendingInvalidation(extras);
DelayedInvalidationsController controller = DelayedInvalidationsController.getInstance();
if (!controller.shouldNotifyInvalidation(extras)) {
controller.addPendingInvalidation(getContext(), account.name, invalidation);
return;
}
// Browser startup is asynchronous, so we will need to wait for startup to finish.
Semaphore semaphore = new Semaphore(0);
// Configure the BrowserParts with all the data it needs.
BrowserParts parts =
getBrowserParts(mApplication, account.name, invalidation, syncResult, semaphore);
startBrowserProcess(parts, syncResult, semaphore);
try {
// This code is only synchronously calling a single native method
// to trigger and asynchronous sync cycle, so 5 minutes is generous.
if (!semaphore.tryAcquire(5, TimeUnit.MINUTES)) {
Log.w(TAG, "Sync request timed out!");
syncResult.stats.numIoExceptions++;
}
} catch (InterruptedException e) {
Log.w(TAG, "Got InterruptedException when trying to request an invalidation.", e);
// Using numIoExceptions so Android will treat this as a soft error.
syncResult.stats.numIoExceptions++;
}
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE)) {
Account signedInAccount = ChromeSigninController.get(getContext()).getSignedInUser();
if (account.equals(signedInAccount)) {
ContentResolver.setIsSyncable(account, authority, 1);
} else {
ContentResolver.setIsSyncable(account, authority, 0);
}
return;
}
PendingInvalidation invalidation = new PendingInvalidation(extras);
DelayedInvalidationsController controller = DelayedInvalidationsController.getInstance();
if (!controller.shouldNotifyInvalidation(extras)) {
controller.addPendingInvalidation(getContext(), account.name, invalidation);
return;
}
// Browser startup is asynchronous, so we will need to wait for startup to finish.
Semaphore semaphore = new Semaphore(0);
// Configure the BrowserParts with all the data it needs.
BrowserParts parts =
getBrowserParts(mApplication, account.name, invalidation, syncResult, semaphore);
startBrowserProcess(parts, syncResult, semaphore);
try {
// This code is only synchronously calling a single native method
// to trigger and asynchronous sync cycle, so 5 minutes is generous.
if (!semaphore.tryAcquire(5, TimeUnit.MINUTES)) {
Log.w(TAG, "Sync request timed out!");
syncResult.stats.numIoExceptions++;
}
} catch (InterruptedException e) {
Log.w(TAG, "Got InterruptedException when trying to request an invalidation.", e);
// Using numIoExceptions so Android will treat this as a soft error.
syncResult.stats.numIoExceptions++;
}
}
public void setAccountSyncable(MovirtAccount account, boolean syncable) {
ContentResolver.setIsSyncable(account.getAccount(), OVirtContract.CONTENT_AUTHORITY, syncable ? 1 : 0);
}
@Override
public void setIsSyncable(Account account, String authority, int syncable) {
ContentResolver.setIsSyncable(account, authority, syncable);
}
public static void requestManualSync(Context context, Bundle args) {
Account account = AccountUtils.getActiveAccount(context);
if (account != null) {
LOGD(TAG, "Requesting manual sync for account " + account.name
+" args=" + args.toString());
args.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
args.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
args.putBoolean(SyncAdapter.EXTRA_SYNC_REMOTE, false);
AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
accountManager.addAccountExplicitly(account, null, null);
// Inform the system that this account is eligible for auto sync when the network is up
ContentResolver.setSyncAutomatically(account, V2exContract.CONTENT_AUTHORITY, true);
// Inform the system that this account supports sync
ContentResolver.setIsSyncable(account, V2exContract.CONTENT_AUTHORITY, 1);
boolean pending = ContentResolver.isSyncPending(account,
V2exContract.CONTENT_AUTHORITY);
if (pending) {
LOGD(TAG, "Warning: sync is PENDING. Will cancel.");
}
boolean active = ContentResolver.isSyncActive(account,
V2exContract.CONTENT_AUTHORITY);
if (active) {
LOGD(TAG, "Warning: sync is ACTIVE. Will cancel.");
}
if (pending || active) {
LOGD(TAG, "Cancelling previously pending/active sync.");
ContentResolver.cancelSync(account, V2exContract.CONTENT_AUTHORITY);
}
LOGD(TAG, "Requesting sync now.");
ContentResolver.requestSync(account, V2exContract.CONTENT_AUTHORITY, args);
} else {
LOGD(TAG, "Can't request manual sync -- no chosen account.");
}
}
private void cancelSync() {
Account acc = User.getAccount();
ContentResolver.setIsSyncable(acc, Contract.AUTHORITY, 0);
ContentResolver.setSyncAutomatically(acc, Contract.AUTHORITY, false);
SettingsUtil.setSyncStatus("N/A");
}
static void enableSync(Context context) {
setComponentEnabled(context, EarthsSyncService.class, true);
final AccountManager am = AccountManager.get(context);
final Account account = makeAccount(context);
am.addAccountExplicitly(account, null, Bundle.EMPTY);
ContentResolver.setIsSyncable(account, EarthsContract.AUTHORITY, 1);
ContentResolver.addPeriodicSync(account, EarthsContract.AUTHORITY,
Bundle.EMPTY, TimeUnit.MINUTES.toSeconds(10));
ContentResolver.setSyncAutomatically(account, EarthsContract.AUTHORITY, true);
}