SyncAdapter - 如何每秒定期同步

时间:2016-05-22 22:18:37

标签: android long-polling polling android-syncadapter

我试图强制我的应用程序每秒执行一次同步,或者每隔4或5秒执行一次同步。但是,我可以使syncadapter同步的最小时间为30-60秒。如何存档这样的行为?

无论我在addPeriodicSync()中设置第二个参数,它都不会低于30秒。         ContentResolver.setMasterSyncAutomatically(真);         ContentResolver.setIsSyncable(mAccount,AUTHORITY,1);

{{1}}

我知道这对于应用程序来说是一种不好的行为,因为它会耗尽电池,并且GCM应该用于从服务器创建推送。 该应用程序用于大学项目演示,因此我需要响应和可呈现。

编辑:

我知道手动同步的可能性:):

提前致谢。

3 个答案:

答案 0 :(得分:0)

我只是假设SyncAdapter不能以这种方式使用,因为它专门设计为不能以这种方式工作。

如果你需要一个应用程序每秒执行一次同步,你应该只是实现一个IntentService,它会以延迟的意图重新启动自己(你可以将延迟设置为1秒),然后在那里进行同步,而不是一个SyncAdapter。

编辑:这是一个示例实现,请不要将其用于除示例之外的任何内容,但我觉得写它有点脏。

public class ContinuousSyncService extends IntentService {

    private static final int DELAY = 1000; // ms

    public ContinuousSyncService() {
        super(ContinuousSyncService.class.getName());
    }

    public static PendingIntent getPendingIntent(@NonNull Context context) {
        Intent intent = new Intent(context, ContinuousSyncService.class);
        return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private void scheduleNextStart(long delay) {
        ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + delay,
                getPendingIntent(this));
    }

    @Override
    protected void onHandleIntent(final Intent intent) {
        sync();
        scheduleNextStart(DELAY);
    }

    private void sync() {
        // Either use ContentResolver.requestSync()
        // Or just put the code from your SyncAdapter.onPerformSync() here
    }

}

答案 1 :(得分:0)

您不能以60秒的间隔安排同步。

您可以通过阅读代码或查看此SO answer

来确认

答案 2 :(得分:0)

我这样做了:

在清单文件中添加权限<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

为同步添加以下方法:

public void syncAllAccountsPeriodically(Context contextAct, long seconds) throws Exception {
    AccountManager manager = AccountManager.get(contextAct);
    Account[] accounts = manager.getAccountsByType("com.google");
    String accountName = "";
    String accountType = "";
    for (Account account : accounts) {
        accountName = account.name;
        accountType = account.type;
        break;
    }

    Account a = new Account(accountName, accountType);
    ContentResolver.addPeriodicSync(a, AUTHORITY,
        Bundle.EMPTY, seconds*1000);
}

希望这对你有所帮助。

相关问题