Importowanie i eksportowanie danych ekranu głównego

Dane ekranu głównego Androida są dostarczane przez klasę LauncherProvider, która rozszerza klasę ContentProvider, co umożliwia importowanie i eksportowanie danych obszaru roboczego Launchera za pomocą XML.

Interakcja z dostawcą treści

Aby wchodzić w interakcje z klasą LaunchProvider, która rozszerza klasę ContentProvider, użyj metody call:

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

Wywołaj klasę LaunchProvider

Aby wywołać klasę LauncherProvider z aplikacji, użyj tego kodu:

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

Parametry

Te stałe są używane w metodzie wywołania:

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

Użyj stałych LauncherProvider z tymi ograniczeniami:

  • Użyj metody contentResolver.call z parametrem EXPORT_LAYOUT_XML, aby wyeksportować reprezentację XML obszaru roboczego programu uruchamiającego.
  • Podczas eksportowania reprezentacja XML jest dostępna w zwróconym pakiecie pod kluczem KEY_LAYOUT.
  • Użyj metody contentResolver.call z parametrem IMPORT_LAYOUT_XML, aby zaimportować reprezentację XML obszaru roboczego programu uruchamiającego.
  • Podczas importowania reprezentacja XML jest podawana jako parametr metody wywołania arg.
  • W przypadku wywołań interfejsu API eksportu i importu pomyślne zakończenie wybranej operacji zwraca wartość success, a przerwane lub nieudane operacje zwracają wartość failure.
  • Wartość success lub failure można pobrać z zwróconego pakietu za pomocą klucza KEY_RESULT.

Przykład znajdziesz w sekcji Wywoływanie klasy LaunchProvider.

Reprezentacja w formacie XML

Podczas importowania i eksportowania korzystaj z tych przewodników dotyczących struktury XML.

  • Aplikacja 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>
    
  • Aplikacja 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>
    
  • Widżet:

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

    <?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>
    
  • Skrót zaawansowany:

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

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

Założenia behawioralne

Poniżej znajdziesz założenia dotyczące zachowania klasy LaunchProvider.

  • Metody są niepodzielne i blokujące.
  • Podczas importowania analogiczne dane w programie uruchamiającym są zastępowane, dzięki czemu pozostają tylko nowo zaimportowane dane.
  • Zaimportowane dane są od razu dostępne. Eksportowanie bezpośrednio po imporcie zwraca nowe dane.