简体   繁体   中英

App keep uploading to Firebase Storage when activity is destroyed

I need to upload a list of images to firebase storage on a button click, and then destroy the activity without any additional action from the user.

The code I have below destroys the activity straight away after the button is clicked, and let the uploading progress still going in the background.

What I want is the activity destroyed after waiting for the uploading progress to finish first.

What should I do to fix this problem?

// on button click
public void send(View view) {

        imageCount = 0;
        imageKey = databaseReference.push().getKey();

        uploadFile( bitmaps );

        intent.putExtra( "location", location);
        intent.putExtra( "description", description);
        intent.putExtra("date", date);
        setResult( 1, intent );

        finish();
    }


private void uploadFile(final ArrayList<Bitmap> bitmaps) {

        FirebaseStorage storage = FirebaseStorage.getInstance();

        for (final Bitmap bitmap : bitmaps) {

            final StorageReference imageRef = storage
                    .getReferenceFromUrl( "gs://example.appspot.com/" )
                    .child( folderName + "/" + UUID.randomUUID() + ".jpeg" );

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress( Bitmap.CompressFormat.JPEG, 20, baos );
            byte[] data = baos.toByteArray();

            UploadTask uploadTask = imageRef.putBytes( data );

            uploadTask.addOnFailureListener( new OnFailureListener() {

                @Override
                public void onFailure(@NonNull Exception exception) {

                    Toast.makeText( LaporActivity.this, "Fail", Toast.LENGTH_SHORT ).show();

                }
            } ).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    imageRef.getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {

                        @Override
                        public void onSuccess(Uri uri) {

                            databaseReference.child( "images" ).child( imageKey ).child( Integer.toString( imageCount ) ).setValue( uri.toString() );

                            imageCount++;

                        }
                    } );
                }
            } );
        }
    }

上传完成后,只需在回调中调用finish()即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM