Pobieranie plików za pomocą Cloud Storage na Androidzie

Cloud Storage dla Firebase umożliwia szybkie i łatwe pobieranie pliki z Cloud Storage udostępniane i zarządzane przez Firebase.

Tworzenie referencji

Aby pobrać plik, utwórz referencję Cloud Storage w pliku, który chcesz pobrać.

Odwołanie możesz utworzyć, dołączając ścieżki podrzędne do katalogu głównego Cloud Storage lub możesz utworzyć odwołanie z istniejącego Adres URL gs:// lub https:// odwołujący się do obiektu w Cloud Storage.

Kotlin+KTX

// Create a storage reference from our app
val storageRef = storage.reference

// Create a reference with an initial file path and name
val pathReference = storageRef.child("images/stars.jpg")

// Create a reference to a file from a Google Cloud Storage URI
val gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg")

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
val httpsReference = storage.getReferenceFromUrl(
    "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg",
)

Java

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Create a reference with an initial file path and name
StorageReference pathReference = storageRef.child("images/stars.jpg");

// Create a reference to a file from a Google Cloud Storage URI
StorageReference gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference httpsReference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

Pobieranie plików

Gdy będziesz mieć już plik referencyjny, możesz pobrać pliki z Cloud Storage Wywołując getBytes() lub getStream(). Jeśli wolisz pobrać plik z inną biblioteką, możesz uzyskać adres URL pobierania za pomocą getDownloadUrl().

Pobierz we wspomnieniu

Pobierz plik do usługi byte[] za pomocą metody getBytes(). To jest jest to najprostszy sposób pobierania pliku, ale musi on wczytać całą zawartość i zapisać go w pamięci. Jeśli poprosisz o plik większy niż dostępny w aplikacji może spowodować awarię aplikacji. Aby zapobiec problemom z pamięcią, getBytes() to maksymalna liczba bajtów, które można pobrać. Ustaw wartość maksymalnego rozmiaru wiesz, że aplikacja poradzi sobie z zakupem aplikacji, albo użyć innej metody pobierania.

Kotlin+KTX

var islandRef = storageRef.child("images/island.jpg")

val ONE_MEGABYTE: Long = 1024 * 1024
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener {
    // Data for "images/island.jpg" is returned, use this as needed
}.addOnFailureListener {
    // Handle any errors
}

Java

StorageReference islandRef = storageRef.child("images/island.jpg");

final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
    @Override
    public void onSuccess(byte[] bytes) {
        // Data for "images/island.jpg" is returns, use this as needed
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

Pobieranie do pliku lokalnego

Metoda getFile() pobiera plik bezpośrednio na urządzenie lokalne. Należy go użyć, jeśli użytkownicy chcą mieć dostęp do pliku offline lub udostępniać go lub inną aplikację. getFile() zwraca wartość DownloadTask, której możesz używać do zarządzania pobieranie i monitorowanie stanu pobierania.

Kotlin+KTX

islandRef = storageRef.child("images/island.jpg")

val localFile = File.createTempFile("images", "jpg")

islandRef.getFile(localFile).addOnSuccessListener {
    // Local temp file has been created
}.addOnFailureListener {
    // Handle any errors
}

Java

islandRef = storageRef.child("images/island.jpg");

File localFile = File.createTempFile("images", "jpg");

islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
        // Local temp file has been created
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

Jeśli chcesz aktywnie zarządzać pobranymi plikami, zobacz Więcej informacji znajdziesz w artykule Zarządzanie pobranymi plikami.

Pobierz dane za pomocą adresu URL

Jeśli Twoja infrastruktura do pobierania jest już oparta na adresach URL lub chcesz adresu URL do udostępnienia, możesz uzyskać adres URL pobierania pliku, wywołując metodę Metoda getDownloadUrl() w referencji Cloud Storage.

Kotlin+KTX

storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
    // Got the download URL for 'users/me/profile.png'
}.addOnFailureListener {
    // Handle any errors
}

Java

storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        // Got the download URL for 'users/me/profile.png'
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

Pobieranie obrazów za pomocą FirebaseUI

FirebaseUI udostępnia proste, konfigurowalne i gotowe do produkcji natywne powiązania mobilne w celu wyeliminowania i promować sprawdzone metody Google. Za pomocą FirebaseUI możesz: szybkie i łatwe pobieranie, buforowanie i wyświetlanie obrazów z Cloud Storage przy użyciu integracji Przesuwanie.

Najpierw dodaj FirebaseUI do app/build.gradle:

dependencies {
    // FirebaseUI Storage only
    implementation 'com.firebaseui:firebase-ui-storage:7.2.0'
}

Następnie możesz wczytywać obrazy bezpośrednio z Cloud Storage do ImageView:

Kotlin+KTX

// Reference to an image file in Cloud Storage
val storageReference = Firebase.storage.reference

// ImageView in your Activity
val imageView = findViewById<ImageView>(R.id.imageView)

// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
Glide.with(context)
    .load(storageReference)
    .into(imageView)

Java

// Reference to an image file in Cloud Storage
StorageReference storageReference = FirebaseStorage.getInstance().getReference();

// ImageView in your Activity
ImageView imageView = findViewById(R.id.imageView);

// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
Glide.with(context)
        .load(storageReference)
        .into(imageView);

Obsługa zmian w cyklu życia aktywności

Pobieranie jest kontynuowane w tle nawet po zmianie cyklu życia aktywności (np. jak prezentację okna lub obrócenie ekranu). wszystkich podłączonych słuchaczy, link pozostanie załączony. Może to spowodować nieoczekiwane wyniki, jeśli wywołana po zatrzymaniu aktywności.

Aby rozwiązać ten problem, zasubskrybuj odbiorców z zakresem aktywności aby automatycznie wyrejestrować je po zatrzymaniu ich aktywności. Następnie skorzystaj z Metoda getActiveDownloadTasks po ponownym uruchomieniu aktywności w celu pobrania danych zadania, które są nadal uruchomione lub niedawno zakończone.

Poniższy przykład obrazuje to i pokazuje, jak zachować miejsce na dane ścieżki referencyjnej.

Kotlin+KTX

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

    // If there's a download in progress, save the reference so you can query it later
    outState.putString("reference", storageRef.toString())
}

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    // If there was a download in progress, get its reference and create a new StorageReference
    val stringRef = savedInstanceState.getString("reference") ?: return

    storageRef = Firebase.storage.getReferenceFromUrl(stringRef)

    // Find all DownloadTasks under this StorageReference (in this example, there should be one)
    val tasks = storageRef.activeDownloadTasks

    if (tasks.size > 0) {
        // Get the task monitoring the download
        val task = tasks[0]

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this) {
            // Success!
            // ...
        }
    }
}

Java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // If there's a download in progress, save the reference so you can query it later
    if (mStorageRef != null) {
        outState.putString("reference", mStorageRef.toString());
    }
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // If there was a download in progress, get its reference and create a new StorageReference
    final String stringRef = savedInstanceState.getString("reference");
    if (stringRef == null) {
        return;
    }
    mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);

    // Find all DownloadTasks under this StorageReference (in this example, there should be one)
    List<FileDownloadTask> tasks = mStorageRef.getActiveDownloadTasks();
    if (tasks.size() > 0) {
        // Get the task monitoring the download
        FileDownloadTask task = tasks.get(0);

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this, new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot state) {
                // Success!
                // ...
            }
        });
    }
}

Obsługa błędów

Błędy mogą występować przy pobieraniu z kilku powodów. Oto niektóre z nich: jeśli plik nie istnieje lub użytkownik nie ma uprawnień dostępu do żądanego pliku. Więcej informacji o błędach znajdziesz w Obsługa błędów sekcji dokumentów.

Pełny przykład

Pełny przykład pliku do pobrania z obsługą błędów znajdziesz poniżej:

Kotlin+KTX

storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener {
    // Use the bytes to display the image
}.addOnFailureListener {
    // Handle any errors
}

Java

storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
    @Override
    public void onSuccess(byte[] bytes) {
        // Use the bytes to display the image
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

Możesz też pobierać i aktualizować metadane. w przypadku plików przechowywanych w Cloud Storage.