运行同步适配器

注意:对于大多数后台处理用例,我们建议使用 WorkManager 作为解决方案。请参阅后台处理指南,了解哪种解决方案最适合您。

在本课程的前几节课中,您学习了如何创建封装数据传输代码的同步适配器组件,以及如何添加可让您将同步适配器插入系统的其他组件。现在,您已具备安装包含同步适配器的应用所需的一切,但您看到的代码都没有实际运行同步适配器。

您应尝试根据时间表或某些事件的间接结果运行同步适配器。例如,您可能希望同步适配器定期运行,在一段时间后或一天中的特定时间运行。您也可能希望在设备上存储的数据发生更改时运行同步适配器。您应避免直接根据用户操作来运行同步适配器,因为这样做无法充分利用同步适配器框架的调度功能。例如,应避免在界面中提供刷新按钮。

您可以通过以下方式运行同步适配器:

当服务器数据发生更改时
在收到表明基于服务器的数据已更改的服务器消息时,运行同步适配器。通过此选项,您可以从服务器向设备刷新数据,而不会因为轮询服务器而降低性能或浪费电池续航时间。
在设备数据改变时运行
当设备上的数据发生更改时运行同步适配器。通过此选项,您可以将修改后的数据从设备发送到服务器,这在需要确保服务器始终具有最新的设备数据时尤其有用。如果您的数据实际存储在 content provider 中,则可以直接实现此方法。如果您使用桩内容提供器,检测数据更改可能会比较困难。
定期
按照您选择的时间间隔或在每天的特定时间运行同步适配器。
点播
根据用户操作运行同步适配器。不过,为了提供最佳的用户体验,您应该主要依赖于其中一种自动化程度更高的方案。使用自动化方案,您可以节省电池电量和网络资源。

本课程的其余部分将更详细地介绍每个选项。

在服务器数据改变时运行同步适配器

如果您的应用从服务器传输数据并且服务器数据经常变化,您可以使用同步适配器在数据变化时执行下载操作。如需运行同步适配器,请让服务器向应用中的 BroadcastReceiver 发送一条特殊消息。为响应此消息,请调用 ContentResolver.requestSync() 以指示同步适配器框架运行您的同步适配器。

Google 云消息传递 (GCM) 提供了让此消息传递系统正常运行所需的服务器和设备组件。与轮询服务器以检索状态相比,使用 GCM 触发传输更可靠且更高效。虽然轮询需要 Service 始终处于活动状态,但 GCM 使用 BroadcastReceiver,它会在收到消息时激活。如果按固定时间间隔轮询,即使没有可用的更新,也会消耗电池电量,而 GCM 仅在需要时发送消息。

注意:如果您使用 GCM 通过向所有已安装您应用的设备广播消息来触发同步适配器,请注意,这些设备几乎会同时收到您的消息。这种情况可能会导致同步适配器的多个实例同时运行,从而导致服务器和网络过载。为避免发生向所有设备广播的情况,您应考虑将同步适配器的启动延迟一段时间,每个时间段因设备而异。

以下代码段展示了如何运行 requestSync() 以响应收到的 GCM 消息:

Kotlin

...
// Constants
// Content provider authority
const val AUTHORITY = "com.example.android.datasync.provider"
// Account type
const val ACCOUNT_TYPE = "com.example.android.datasync"
// Account
const val ACCOUNT = "default_account"
// Incoming Intent key for extended data
const val KEY_SYNC_REQUEST = "com.example.android.datasync.KEY_SYNC_REQUEST"
...
class GcmBroadcastReceiver : BroadcastReceiver() {
    ...
    override fun onReceive(context: Context, intent: Intent) {
        // Get a GCM object instance
        val gcm: GoogleCloudMessaging = GoogleCloudMessaging.getInstance(context)
        // Get the type of GCM message
        val messageType: String? = gcm.getMessageType(intent)
        /*
         * Test the message type and examine the message contents.
         * Since GCM is a general-purpose messaging system, you
         * may receive normal messages that don't require a sync
         * adapter run.
         * The following code tests for a a boolean flag indicating
         * that the message is requesting a transfer from the device.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE == messageType
            && intent.getBooleanExtra(KEY_SYNC_REQUEST, false)) {
            /*
             * Signal the framework to run your sync adapter. Assume that
             * app initialization has already created the account.
             */
            ContentResolver.requestSync(mAccount, AUTHORITY, null)
            ...
        }
        ...
    }
    ...
}

Java

public class GcmBroadcastReceiver extends BroadcastReceiver {
    ...
    // Constants
    // Content provider authority
    public static final String AUTHORITY = "com.example.android.datasync.provider";
    // Account type
    public static final String ACCOUNT_TYPE = "com.example.android.datasync";
    // Account
    public static final String ACCOUNT = "default_account";
    // Incoming Intent key for extended data
    public static final String KEY_SYNC_REQUEST =
            "com.example.android.datasync.KEY_SYNC_REQUEST";
    ...
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get a GCM object instance
        GoogleCloudMessaging gcm =
                GoogleCloudMessaging.getInstance(context);
        // Get the type of GCM message
        String messageType = gcm.getMessageType(intent);
        /*
         * Test the message type and examine the message contents.
         * Since GCM is a general-purpose messaging system, you
         * may receive normal messages that don't require a sync
         * adapter run.
         * The following code tests for a a boolean flag indicating
         * that the message is requesting a transfer from the device.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)
            &&
            intent.getBooleanExtra(KEY_SYNC_REQUEST)) {
            /*
             * Signal the framework to run your sync adapter. Assume that
             * app initialization has already created the account.
             */
            ContentResolver.requestSync(mAccount, AUTHORITY, null);
            ...
        }
        ...
    }
    ...
}

在内容提供器数据改变时运行同步适配器

如果您的应用在 content provider 中收集数据,并且您希望在每次更新提供程序时更新服务器,则可以将应用设置为自动运行同步适配器。为此,您需要为 content provider 注册一个观察器。当 content provider 中的数据发生更改时,content provider 框架会调用观察器。在观察器中,调用 requestSync() 以指示框架运行您的同步适配器。

注意:如果您使用的是桩内容提供器,那么该内容提供器中没有任何数据,并且系统永远不会调用 onChange()。在这种情况下,您必须提供自己的机制来检测设备数据的变化。此机制还负责在数据发生更改时调用 requestSync()

如需为 content provider 创建观察器,请扩展 ContentObserver 类并同时实现其 onChange() 方法的两种形式。在 onChange() 中,调用 requestSync() 以启动同步适配器。

如需注册观察者,请在对 registerContentObserver() 的调用中将其作为参数传递。在此调用中,您还必须传入想要查看的数据的内容 URI。内容提供程序框架会将此监视 URI 与作为参数传入到用于修改提供程序(如 ContentResolver.insert())的 ContentResolver 方法的内容 URI 进行比较。如果匹配,则调用 ContentObserver.onChange() 实现。

以下代码段展示了如何定义在表发生更改时调用 requestSync()ContentObserver

Kotlin

// Constants
// Content provider scheme
const val SCHEME = "content://"
// Content provider authority
const val AUTHORITY = "com.example.android.datasync.provider"
// Path for the content provider table
const val TABLE_PATH = "data_table"
...
class MainActivity : FragmentActivity() {
    ...
    // A content URI for the content provider's data table
    private lateinit var uri: Uri
    // A content resolver for accessing the provider
    private lateinit var mResolver: ContentResolver
    ...
    inner class TableObserver(...) : ContentObserver(...) {
        /*
         * Define a method that's called when data in the
         * observed content provider changes.
         * This method signature is provided for compatibility with
         * older platforms.
         */
        override fun onChange(selfChange: Boolean) {
            /*
             * Invoke the method signature available as of
             * Android platform version 4.1, with a null URI.
             */
            onChange(selfChange, null)
        }

        /*
         * Define a method that's called when data in the
         * observed content provider changes.
         */
        override fun onChange(selfChange: Boolean, changeUri: Uri?) {
            /*
             * Ask the framework to run your sync adapter.
             * To maintain backward compatibility, assume that
             * changeUri is null.
             */
            ContentResolver.requestSync(account, AUTHORITY, null)
        }
        ...
    }
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        // Get the content resolver object for your app
        mResolver = contentResolver
        // Construct a URI that points to the content provider data table
        uri = Uri.Builder()
                .scheme(SCHEME)
                .authority(AUTHORITY)
                .path(TABLE_PATH)
                .build()
        /*
         * Create a content observer object.
         * Its code does not mutate the provider, so set
         * selfChange to "false"
         */
        val observer = TableObserver(false)
        /*
         * Register the observer for the data table. The table's path
         * and any of its subpaths trigger the observer.
         */
        mResolver.registerContentObserver(uri, true, observer)
        ...
    }
    ...
}

Java

public class MainActivity extends FragmentActivity {
    ...
    // Constants
    // Content provider scheme
    public static final String SCHEME = "content://";
    // Content provider authority
    public static final String AUTHORITY = "com.example.android.datasync.provider";
    // Path for the content provider table
    public static final String TABLE_PATH = "data_table";
    // Account
    public static final String ACCOUNT = "default_account";
    // Global variables
    // A content URI for the content provider's data table
    Uri uri;
    // A content resolver for accessing the provider
    ContentResolver mResolver;
    ...
    public class TableObserver extends ContentObserver {
        /*
         * Define a method that's called when data in the
         * observed content provider changes.
         * This method signature is provided for compatibility with
         * older platforms.
         */
        @Override
        public void onChange(boolean selfChange) {
            /*
             * Invoke the method signature available as of
             * Android platform version 4.1, with a null URI.
             */
            onChange(selfChange, null);
        }
        /*
         * Define a method that's called when data in the
         * observed content provider changes.
         */
        @Override
        public void onChange(boolean selfChange, Uri changeUri) {
            /*
             * Ask the framework to run your sync adapter.
             * To maintain backward compatibility, assume that
             * changeUri is null.
             */
            ContentResolver.requestSync(mAccount, AUTHORITY, null);
        }
        ...
    }
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Get the content resolver object for your app
        mResolver = getContentResolver();
        // Construct a URI that points to the content provider data table
        uri = new Uri.Builder()
                  .scheme(SCHEME)
                  .authority(AUTHORITY)
                  .path(TABLE_PATH)
                  .build();
        /*
         * Create a content observer object.
         * Its code does not mutate the provider, so set
         * selfChange to "false"
         */
        TableObserver observer = new TableObserver(false);
        /*
         * Register the observer for the data table. The table's path
         * and any of its subpaths trigger the observer.
         */
        mResolver.registerContentObserver(uri, true, observer);
        ...
    }
    ...
}

定期运行同步适配器

您可以定期运行同步适配器,只需设置两次运行之间的等待时间,和/或安排在一天中的特定时间运行即可。定期运行同步适配器可让您大致达到服务器的更新间隔。

同样,您也可以将同步适配器安排在夜间运行,以便在服务器相对空闲时从设备上传数据。大多数用户会在夜间让设备保持开机状态并接通电源,因此这段时间通常可以使用。此外,设备不会与您的同步适配器同时运行其他任务。不过,如果采用这种方法,您需要确保每个设备在略微不同的时间触发数据传输。如果所有设备同时运行您的同步适配器,则可能会导致您的服务器和手机提供商数据网络过载。

一般来说,如果您的用户不需要即时更新,但希望定期更新,则定期运行比较合适。此外,如果您希望在最新数据的可用性与运行较少且不会过度使用设备资源的同步适配器运行之间取得平衡,则定期运行也非常合适。

如需定期运行同步适配器,请调用 addPeriodicSync()。这会安排您的同步适配器在经过一定时间后运行。由于同步适配器框架必须考虑其他同步适配器的执行并尝试最大限度地提高电池效率,因此经过的时间可能会有几秒钟的差异。此外,如果网络不可用,框架将不会运行您的同步适配器。

请注意,addPeriodicSync() 不会在一天中的特定时间运行同步适配器。如需在每天大致相同的时间运行同步适配器,可以使用重复闹钟作为触发器。AlarmManager 的参考文档中对重复闹钟进行了更详细的介绍。如果您使用 setInexactRepeating() 方法设置存在一些变化的时段触发器,您仍应随机设置开始时间,以确保错开同步适配器在不同设备上运行。

addPeriodicSync() 方法不会停用 setSyncAutomatically(),因此您可能会在相对较短的时间段内运行多次同步。此外,调用 addPeriodicSync() 时只允许使用几个同步适配器控制标志;addPeriodicSync() 的参考文档中介绍了不允许使用的标志。

以下代码段展示了如何安排定期运行同步适配器:

Kotlin

// Content provider authority
const val AUTHORITY = "com.example.android.datasync.provider"
// Account
const val ACCOUNT = "default_account"
// Sync interval constants
const val SECONDS_PER_MINUTE = 60L
const val SYNC_INTERVAL_IN_MINUTES = 60L
const val SYNC_INTERVAL = SYNC_INTERVAL_IN_MINUTES * SECONDS_PER_MINUTE
...
class MainActivity : FragmentActivity() {
    ...
    // A content resolver for accessing the provider
    private lateinit var mResolver: ContentResolver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        // Get the content resolver for your app
        mResolver = contentResolver
        /*
         * Turn on periodic syncing
         */
        ContentResolver.addPeriodicSync(
                mAccount,
                AUTHORITY,
                Bundle.EMPTY,
                SYNC_INTERVAL)
        ...
    }
    ...
}

Java

public class MainActivity extends FragmentActivity {
    ...
    // Constants
    // Content provider authority
    public static final String AUTHORITY = "com.example.android.datasync.provider";
    // Account
    public static final String ACCOUNT = "default_account";
    // Sync interval constants
    public static final long SECONDS_PER_MINUTE = 60L;
    public static final long SYNC_INTERVAL_IN_MINUTES = 60L;
    public static final long SYNC_INTERVAL =
            SYNC_INTERVAL_IN_MINUTES *
            SECONDS_PER_MINUTE;
    // Global variables
    // A content resolver for accessing the provider
    ContentResolver mResolver;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Get the content resolver for your app
        mResolver = getContentResolver();
        /*
         * Turn on periodic syncing
         */
        ContentResolver.addPeriodicSync(
                mAccount,
                AUTHORITY,
                Bundle.EMPTY,
                SYNC_INTERVAL);
        ...
    }
    ...
}

按需运行同步适配器

响应用户请求运行同步适配器是最不可取的同步适配器运行策略。该框架经过专门设计,可在按计划运行同步适配器时节省电池电量。根据数据变化运行同步的选项可以有效地利用电池电量,因为电量用于提供新数据。

相比之下,允许用户按需运行同步意味着同步会自行运行,这会导致网络和电源资源的使用效率低下。此外,按需提供同步会导致用户即使没有证据表明数据已更改,也请求同步,而运行不刷新数据的同步是对电池电量的无效使用。一般来说,您的应用应该使用其他信号触发同步,或者安排定期运行同步,而无需用户操作。

但是,如果您仍希望按需运行同步适配器,请为手动运行同步适配器设置同步适配器标志,然后调用 ContentResolver.requestSync()

使用以下标志运行按需传输:

SYNC_EXTRAS_MANUAL
强制手动同步。同步适配器框架会忽略现有设置,如由 setSyncAutomatically() 设置的标志。
SYNC_EXTRAS_EXPEDITED
强制立即开始同步。如果不设置此值,系统可能会等待几秒钟再运行同步请求,因为它会尝试在短时间内调度大量请求,从而优化电池使用。

以下代码段展示了如何调用 requestSync() 来响应按钮点击操作:

Kotlin

// Constants
// Content provider authority
val AUTHORITY = "com.example.android.datasync.provider"
// Account type
val ACCOUNT_TYPE = "com.example.android.datasync"
// Account
val ACCOUNT = "default_account"
...
class MainActivity : FragmentActivity() {
    ...
    // Instance fields
    private lateinit var mAccount: Account
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        /*
         * Create the placeholder account. The code for CreateSyncAccount
         * is listed in the lesson Creating a Sync Adapter
         */

        mAccount = createSyncAccount()
        ...
    }

    /**
     * Respond to a button click by calling requestSync(). This is an
     * asynchronous operation.
     *
     * This method is attached to the refresh button in the layout
     * XML file
     *
     * @param v The View associated with the method call,
     * in this case a Button
     */
    fun onRefreshButtonClick(v: View) {
        // Pass the settings flags by inserting them in a bundle
        val settingsBundle = Bundle().apply {
            putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
            putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
        }
        /*
         * Request the sync for the default account, authority, and
         * manual sync settings
         */
        ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle)
    }

Java

public class MainActivity extends FragmentActivity {
    ...
    // Constants
    // Content provider authority
    public static final String AUTHORITY =
            "com.example.android.datasync.provider";
    // Account type
    public static final String ACCOUNT_TYPE = "com.example.android.datasync";
    // Account
    public static final String ACCOUNT = "default_account";
    // Instance fields
    Account mAccount;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        /*
         * Create the placeholder account. The code for CreateSyncAccount
         * is listed in the lesson Creating a Sync Adapter
         */

        mAccount = CreateSyncAccount(this);
        ...
    }
    /**
     * Respond to a button click by calling requestSync(). This is an
     * asynchronous operation.
     *
     * This method is attached to the refresh button in the layout
     * XML file
     *
     * @param v The View associated with the method call,
     * in this case a Button
     */
    public void onRefreshButtonClick(View v) {
        // Pass the settings flags by inserting them in a bundle
        Bundle settingsBundle = new Bundle();
        settingsBundle.putBoolean(
                ContentResolver.SYNC_EXTRAS_MANUAL, true);
        settingsBundle.putBoolean(
                ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        /*
         * Request the sync for the default account, authority, and
         * manual sync settings
         */
        ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle);
    }