Android'de Cloud Storage ile dosya indirme

Cloud Storage for Firebase, indirme işlemini hızlı ve kolay bir şekilde gerçekleştirmenize olanak tanır Cloud Storage'daki dosyaları Firebase tarafından sağlanır ve yönetilir.

Referans Oluşturma

Bir dosyayı indirmek için önce Cloud Storage referansı oluşturma dosyasını seçin.

Cloud Storage paketine göz atabilir veya mevcut bir paketten referans oluşturabilirsiniz. Cloud Storage'da bir nesneye referans veren gs:// veya https:// URL'si.

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

Dosyaları İndir

Referans edindikten sonra dosyaları Cloud Storage'dan indirebilirsiniz getBytes() veya getStream() numaralı telefonu arayarak. Dosyayı indirmeyi tercih ederseniz başka bir kitaplıkla, getDownloadUrl() ile bir indirme URL'si alabilirsiniz.

Bellekte indir

Dosyayı, getBytes() yöntemini kullanarak bir byte[] konumuna indirin. Bu, bir dosyayı indirmenin en kolay yoludur, ancak dosyanın hafızaya alabilirsiniz. Uygulamanızın kullanılabilir olduğundan daha büyük bir dosya için istekte bulunursanız uygulamanız kilitlenir. Bellek sorunlarına karşı koruma sağlamak için getBytes() indirilmeleri maksimum bayttır. Maksimum boyutu bir değere ayarla veya başka bir indirme yöntemi kullanabilirsiniz.

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

Yerel dosyaya indir

getFile() yöntemi, dosyayı doğrudan yerel bir cihaza indirir. Bu seçeneği aşağıdaki durumlarda kullanın: Kullanıcılarınız çevrimdışıyken dosyaya erişmek veya dosyayı bir ekleyebilirsiniz. getFile(), yönetmek için kullanabileceğiniz bir DownloadTask döndürür yardımcı olabilir ve indirme işleminin durumunu izleyebilirsiniz.

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

İndirme işleminizi etkin bir şekilde yönetmek istiyorsanız Daha fazla bilgi için İndirilenleri Yönetme başlıklı makaleyi inceleyin.

Verileri URL Yoluyla İndir

URL'leri temel alan bir indirme altyapınız varsa veya paylaşmak istiyorsanız, getDownloadUrl() yöntemini çağırın.

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

FirebaseUI ile Resim İndirme

FirebaseUI basit, özelleştirilebilir ve üretime hazır yerel mobil bağlamaları kullanır. Google'ın en iyi uygulamalarını tanıtırız. FirebaseUI ile şunları yapabilirsiniz: hızlı ve kolay bir şekilde indirme, önbelleğe alma ve görüntüleme Cloud Storage'dan edindiğimiz entegrasyon sayesinde Kaydır.

İlk olarak FirebaseUI'yi app/build.gradle sayfanıza ekleyin:

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

Ardından, görüntüleri doğrudan Cloud Storage'dan bir ImageView hizmetine yükleyebilirsiniz:

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);

Etkinlik Yaşam Döngüsü Değişikliklerini Yönetme

Etkinlik yaşam döngüsü değiştiğinde bile indirme işlemleri arka planda devam eder (örneğin, (ör. iletişim kutusu gösterme veya ekranı döndürme) Eklediğiniz dinleyiciler ekli olarak kalacak. Bu durum, kalite standartlarının , etkinlik durdurulduktan sonra çağrılır.

Dinleyicilerinize etkinlik kapsamı aboneliği sunarak bu sorunu çözebilirsiniz Etkinlik durduğunda çocuğunuzun kaydını otomatik olarak iptal edebilirsiniz. Daha sonra, İndirmeyi almak için etkinlik yeniden başlatıldığında getActiveDownloadTasks yöntemi görevleri tamamlamak için kullanılabilir.

Aşağıdaki örnekte bu ve depolama alanının nasıl kalıcı olarak tutulacağı gösterilmiştir. referans yolu kullanılır.

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!
                // ...
            }
        });
    }
}

Hataları Giderme

İndirme sırasında hataların oluşmasının birkaç nedeni vardır: dosya mevcut değil veya kullanıcının istenen dosyaya erişim izni yok. Hatalarla ilgili daha fazla bilgiyi şurada bulabilirsiniz: Hataları İşleme bölümünde bulabilirsiniz.

Tam Örnek

Hata işleme kullanılan bir indirme örneği aşağıda verilmiştir:

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

Ayrıca meta verileri alıp güncelleyebilirsiniz Google Cloud Storage'da depolanan dosyaları ifade eder.