Android'de Cloud Storage ile dosya indirme

Cloud Storage for Firebase, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketinden dosyaları hızlı ve kolay bir şekilde indirmenize olanak tanır.

Referans Oluşturma

Bir dosyayı indirmek için önce indirmek istediğiniz dosyaya Cloud Storage referans oluşturun.

Alt yolları Cloud Storage paketinize ekleyerek referans oluşturabilir veya Cloud Storage içindeki bir nesneye referans veren mevcut bir gs:// ya da https:// URL'den referans oluşturabilirsiniz.

Kotlin

// 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ınız olduğunda Cloud Storage adresinden getBytes() veya getStream() numaralarını arayarak dosya indirebilirsiniz. Dosyayı başka bir kitaplıkla indirmeyi tercih ederseniz getDownloadUrl() ile indirme URL'si alabilirsiniz.

Belleğe indirme

Dosyayı getBytes() yöntemiyle byte[] konumuna indirin. Bu, dosya indirmenin en kolay yoludur ancak dosyanızın tüm içeriğini belleğe yüklemesi gerekir. Uygulamanızın kullanılabilir belleğinden daha büyük bir dosya isteğinde bulunursanız uygulamanız kilitlenir. Bellek sorunlarına karşı koruma sağlamak için getBytes() maksimum bayt miktarı indirir. Maksimum boyutu, uygulamanızın işleyebileceği bir değere ayarlayın veya başka bir indirme yöntemi kullanın.

Kotlin

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 bir dosyaya indirme

getFile() yöntemi, dosyayı doğrudan yerel bir cihaza indirir. Kullanıcılarınızın dosyalara çevrimdışı erişmek veya dosyayı farklı bir uygulamada paylaşmak istemesi durumunda bu işlevi kullanın. getFile(), indirme işleminizi yönetmek ve indirme durumunu izlemek için kullanabileceğiniz bir DownloadTask döndürür.

Kotlin

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 İndirme İşlemlerini Yönetme başlıklı makaleyi inceleyin.

URL ile veri indirme

URL'lere dayalı bir indirme altyapınız varsa veya yalnızca paylaşmak için bir URL istiyorsanız getDownloadUrl() referansında Cloud Storage yöntemini çağırarak bir dosyanın indirme URL'sini alabilirsiniz.

Kotlin

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 indirme

FirebaseUI, standart kodu ortadan kaldırmak ve Google'ın en iyi uygulamalarını desteklemek için basit, özelleştirilebilir ve üretime hazır yerel mobil bağlamalar sağlar. FirebaseUI'yı kullanarak Cloud Storage'daki resimleri Glide ile entegrasyonumuz sayesinde hızlı ve kolay bir şekilde indirebilir, önbelleğe alabilir ve görüntüleyebilirsiniz.

Öncelikle FirebaseUI'ı app/build.gradle ekleyin:

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

Ardından, Cloud Storage uygulamasından doğrudan ImageView içine resim yükleyebilirsiniz:

Kotlin

// 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 İşleme

İndirmeler, etkinlik yaşam döngüsü değişse bile (ör. iletişim kutusu gösterilmesi veya ekranın döndürülmesi) arka planda devam eder. Eklediğiniz dinleyiciler de ekli kalır. Bu işlevler, etkinlik durdurulduktan sonra çağrılırsa beklenmedik sonuçlara neden olabilir.

Bu sorunu, dinleyicilerinizi etkinlik kapsamıyla abone ederek ve etkinlik durduğunda otomatik olarak kayıtlarını silerek çözebilirsiniz. Ardından, etkinlik yeniden başladığında hala devam eden veya yakın zamanda tamamlanan indirme görevlerini almak için getActiveDownloadTasks yöntemini kullanın.

Aşağıdaki örnekte bu durum gösterilmekte ve kullanılan depolama referans yolunun nasıl kalıcı hale getirileceği açıklanmaktadır.

Kotlin

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ı İşleme

İndirme sırasında hataların oluşmasının birkaç nedeni vardır. Örneğin, dosya mevcut olmayabilir veya kullanıcının istenen dosyaya erişme izni olmayabilir. Hatalar hakkında daha fazla bilgiyi dokümanların Hataları İşleme bölümünde bulabilirsiniz.

Tam Örnek

Aşağıda, hata işlemeyle yapılan bir indirme işleminin tam örneği gösterilmektedir:

Kotlin

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, Cloud Storage'da depolanan dosyalar için meta verileri alıp güncelleyebilirsiniz.