导入和导出主屏幕数据

Android 主屏幕数据由 LauncherProvider 类提供,该类扩展了 ContentProvider,允许使用 XML 导入和导出启动器工作区数据。

与内容提供方互动

如需与扩展 ContentProviderLaunchProvider 类互动,请使用 call 方法:

class LauncherProvider : ContentProvider {
    public Bundle call(String method, String arg, Bundle extras);
}

调用 LaunchProvider 类

如需从应用中调用 LauncherProvider 类,请使用以下代码:

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()
    }
}

参数

以下常量用于调用方法:

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";
}

使用 LauncherProvider 常量,并遵循以下限制:

  • 使用 contentResolver.call 方法,并将 EXPORT_LAYOUT_XML 作为方法参数,以导出启动器工作区的 XML 表示形式。
  • 在导出期间,可以使用 KEY_LAYOUT 键在返回的软件包中访问 XML 表示形式。
  • 使用 contentResolver.call 方法(以 IMPORT_LAYOUT_XML 作为方法参数)导入启动器工作区的 XML 表示形式。
  • 在导入期间,XML 表示形式会作为调用方法的 arg 参数提供。
  • 对于导出和导入 API 调用,如果所选操作成功完成,则返回 success;如果操作中断或失败,则返回 failure
  • 可以使用 KEY_RESULT 键在返回的软件包中检索 successfailure 值。

如需查看示例,请参阅调用 LaunchProvider 类

XML 表示法

在导入和导出期间,请参考以下有关 XML 结构的指南。

  • 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>
    
  • 底部区域应用:

    <?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>
    
  • widget:

    <?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>
    
  • 文件夹:

    <?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>
    
  • 深度快捷方式:

    <?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <workspace>
      <shortcut shortcutId="shortcut2" packageName="com.google.android.apps.nexuslauncher.tests" />
    </workspace>
    
  • 应用对:

    <?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>
    

行为假设

以下是 LaunchProvider 类的行为假设。

  • 方法是原子且阻塞的。
  • 在导入过程中,启动器中的类似数据会被覆盖,只留下新导入的数据。
  • 导入的数据可立即访问;在导入后立即导出可返回新数据。