Dữ liệu màn hình chính Android được cung cấp bởi lớp LauncherProvider, mở rộng ContentProvider, cho phép nhập và xuất dữ liệu không gian làm việc của Trình chạy bằng XML.
Tương tác với nhà cung cấp nội dung
Để tương tác với lớp LaunchProvider (mở rộng ContentProvider), hãy sử dụng phương thức call:
class LauncherProvider : ContentProvider {
    public Bundle call(String method, String arg, Bundle extras);
}
Gọi lớp LaunchProvider
Để gọi lớp LauncherProvider từ ứng dụng, hãy dùng nội dung sau:
class YourClass {
    /**
     * This method imports Launcher workspace data as a XML string. Calling this method clears the old
     * data model within Launcher and replaces it with the imported data. It should be noted
     * that it doesn't need to clear all the Launcher's data, just what is similar to what is being imported.
     */
    fun importLauncherData(xmlRepresentation: String, ctx: Context): Boolean {
        val uri = try {
            getLauncherProviderUri(ctx)
        } catch (e: IllegalStateException) {
            Log.e(TAG, "Failed to get launcher provider URI", e)
            return false
        }
        val bundle = ctx.contentResolver.call(
            uri,
            LauncherProviderConstants.METHOD_IMPORT_LAYOUT_XML,
            xmlRepresentation,
            null,
        )
        return LauncherProviderConstants.SUCCESS
            .equals(bundle.getBoolean(LauncherProviderConstants.KEY_RESULT))
    }
    /**
     * Use this function to retrieve an XML string representation of the Launcher's Workspace.
     * This method doesn't return what the user sees on their home screen,
     * but rather what is in their data model at the moment it's called.
     */
    fun exportLauncherData(xmlRepresentation: String, ctx: Context): String {
        val uri = try {
            getLauncherProviderUri(ctx)
        } catch (e: IllegalStateException) {
            Log.e(TAG, "Failed to get launcher provider URI", e)
            return ""
        }
        val bundle = ctx.contentResolver.call(
            uri,
            LauncherProviderConstants.METHOD_EXPORT_LAYOUT_XML,
            null,
            null,
        )
        if (LauncherProviderConstants.FAILURE
            .equals(bundle.getBoolean(LauncherProviderConstants.KEY_RESULT))) {
            Log.e(TAG, "failed to export launcher data; review previous logs for the cause.")
        }
        return bundle.getString(LauncherProviderConstants.KEY_LAYOUT, "")
    }
    /**
     * Returns a Uri for interacting with Launcher's ContentProvider.
     *
     * Not all Launchers implement this api. This method throws an IllegalStateException
     * if the Launcher doesn't support it.
     */
    private fun getLauncherProviderUri(ctx: Context): Uri {
        val homeIntent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
        val launcherPackage: String =
            ctx.packageManager
                .resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY)
                ?.activityInfo
                ?.packageName ?: throw IllegalStateException("No launcher package found")
        val authority = "${launcherPackage}.settings"
        ctx.packageManager.resolveContentProvider(authority, 0)
            ?: throw IllegalStateException(
                "Launcher package '$launcherPackage' does not support LauncherProvider",
            )
        return "content://$authority".toUri()
    }
}
Tham số
Các hằng số này được dùng trong phương thức gọi:
object LauncherProviderConstants {
    // Valid arg parameters for export and import operations
    private static final String METHOD_EXPORT_LAYOUT_XML = "EXPORT_LAYOUT_XML";
    private static final String METHOD_IMPORT_LAYOUT_XML = "IMPORT_LAYOUT_XML";
    // Bundle key and value set for determining if operation completed successfully or not
    private static final String KEY_RESULT = "KEY_RESULT";
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";
    // Bundle key used to store exported XML-string representation of Launcher's workspace layout
    // and item metadata
    private static final String KEY_LAYOUT = "KEY_LAYOUT";
}
Sử dụng hằng số LauncherProvider với các quy tắc ràng buộc sau:
- Sử dụng phương thức contentResolver.callvớiEXPORT_LAYOUT_XMLlàm tham số phương thức để xuất một bản trình bày XML của không gian làm việc trên trình chạy.
- Trong quá trình xuất, bạn có thể truy cập vào biểu thị XML trong gói được trả về bằng khoá KEY_LAYOUT.
- Sử dụng phương thức contentResolver.callvớiIMPORT_LAYOUT_XMLlàm tham số phương thức để nhập một bản trình bày XML của không gian làm việc trên trình chạy.
- Trong quá trình nhập, biểu thị XML được cung cấp dưới dạng tham số argcủa phương thức gọi.
- Đối với cả lệnh gọi API xuất và nhập, việc hoàn tất thành công thao tác đã chọn sẽ trả về success, còn các thao tác bị gián đoạn hoặc không thành công sẽ trả vềfailure.
- Bạn có thể truy xuất giá trị successhoặcfailuretrong gói được trả về bằng khoáKEY_RESULT.
Để xem ví dụ, hãy xem phần Gọi lớp LaunchProvider.
Biểu thị bằng XML
Hãy sử dụng các hướng dẫn sau đây về cấu trúc XML trong quá trình nhập và xuất.
- Ứng dụng Workspace: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace rows="4" columns="5"> <autoinstall container="desktop" x="1" y="1" screen="0" className="com.android.launcher3.tests.Activity2" packageName="com.google.android.apps.nexuslauncher" /> </workspace>
- Ứng dụng Hotseat: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace> <autoinstall container="hotseat" rank="0" className="com.android.launcher3.tests.Activity2" packageName="com.google.android.apps.nexuslauncher" /> </workspace>
- Tiện ích: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace> <appwidget container="desktop" spanX="2" spanY="2" x="0" y="1" screen="0" className="PlaceholderWidget" packageName="com.test.pending" /> </workspace>
- Thư mục: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace> <folder container="desktop" x="1" y="1" screen="1" titleText="CustomFolder"> <autoinstall className="com.android.launcher3.tests.Activity1" packageName="com.google.android.apps.nexuslauncher" /> <autoinstall className="com.android.launcher3.tests.Activity2" packageName="com.google.android.apps.nexuslauncher" /> <autoinstall className="com.android.launcher3.tests.Activity3" packageName="com.google.android.apps.nexuslauncher" /> </folder> </workspace>
- Lối tắt sâu: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace> <shortcut shortcutId="shortcut2" packageName="com.google.android.apps.nexuslauncher.tests" /> </workspace>
- Cặp ứng dụng: - <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <workspace> <apppair container="desktop" x="1" y="1" screen="1" titleText="CustomFolder"> <autoinstall className="com.android.launcher3.tests.Activity1" packageName="com.google.android.apps.nexuslauncher" /> <autoinstall className="com.android.launcher3.tests.Activity2" packageName="com.google.android.apps.nexuslauncher" /> </apppair> </workspace>
Giả định về hành vi
Sau đây là các giả định về hành vi đối với lớp LaunchProvider.
- Các phương thức này là nguyên tử và chặn.
- Dữ liệu tương tự trong trình chạy sẽ bị ghi đè trong quá trình nhập, chỉ còn lại dữ liệu mới nhập.
- Bạn có thể truy cập ngay vào dữ liệu đã nhập; việc xuất dữ liệu ngay sau khi nhập sẽ trả về dữ liệu mới.
