Android'de Cloud Storage ile dosyaları indirin

Firebase için Cloud Storage, 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ştur

Bir dosyayı indirmek için öncelikle indirmek istediğiniz dosyaya yönelik bir Cloud Storage referansı oluşturun .

Cloud Storage paketinizin köküne alt yollar ekleyerek bir referans oluşturabilir veya Cloud Storage'daki bir nesneye referans veren mevcut bir gs:// veya https:// URL'sinden bir referans oluşturabilirsiniz.

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ı indir

Bir referansa sahip olduğunuzda, getBytes() veya getStream() işlevini çağırarak Cloud Storage'dan dosya indirebilirsiniz. Dosyayı başka bir kitaplıkla indirmeyi tercih ederseniz getDownloadUrl() ile bir indirme URL'si alabilirsiniz.

Belleğe indir

Dosyayı getBytes() yöntemiyle bir byte[] a indirin. Bu, bir dosyayı 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 talep ederseniz uygulamanız çökecektir. Bellek sorunlarına karşı koruma sağlamak için getBytes() indirilmesi maksimum miktarda bayt alır. Maksimum boyutu, uygulamanızın işleyebileceğini bildiğiniz bir şeye ayarlayın veya başka bir indirme yöntemi kullanın.

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

getFile() yöntemi, bir dosyayı doğrudan yerel bir aygıta indirir. Kullanıcılarınız dosyaya çevrimdışıyken erişmek veya dosyayı farklı bir uygulamada paylaşmak istiyorsa bunu kullanın. getFile() indirme işleminizi yönetmek ve indirme durumunu izlemek için kullanabileceğiniz bir DownloadTask döndürür.

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 aktif olarak yönetmek istiyorsanız daha fazla bilgi için İndirmeleri Yönetme bölümüne bakın.

URL aracılığıyla Verileri İndir

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

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 Görsellerin İndirilmesi

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

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

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

Daha sonra görüntüleri doğrudan Cloud Storage'dan ImageView 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

İndirmeler, etkinlik yaşam döngüsü değişikliklerinden sonra bile (bir iletişim kutusunun sunulması veya ekranın döndürülmesi gibi) arka planda devam eder. Eklediğiniz dinleyiciler de bağlı kalacaktır. Bu, etkinlik durdurulduktan sonra çağrılmaları durumunda beklenmeyen sonuçlara neden olabilir.

Etkinlik durduğunda kayıtlarını otomatik olarak iptal edecek bir etkinlik kapsamıyla dinleyicilerinize abone olarak bu sorunu çözebilirsiniz. Daha sonra, halen çalışmakta olan veya yakın zamanda tamamlanan indirme görevlerini almak için etkinlik yeniden başlatıldığında getActiveDownloadTasks yöntemini kullanın.

Aşağıdaki örnek bunu göstermektedir ve ayrıca kullanılan depolama referans yolunun nasıl kalıcı hale getirileceğini de göstermektedir.

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

Dosyanın mevcut olmaması veya kullanıcının istenen dosyaya erişim iznine sahip olmaması da dahil olmak üzere indirme sırasında hataların ortaya çıkmasının çeşitli nedenleri vardır. Hatalarla ilgili daha fazla bilgiyi dokümanların Hataları İşleme bölümünde bulabilirsiniz.

Tam Örnek

Hata işlemeli bir indirmenin tam örneği aşağıda gösterilmektedir:

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 Cloud Storage'da depolanan dosyalara ilişkin meta verileri alabilir ve güncelleyebilirsiniz .