简体   繁体   中英

Android Firebase Storage Keep Uploading When Activity Is Destroyed

When someone using my android app is uploading a video to Firebase Storage, I want the video to upload even when the activity is destroyed. I tried using asynctask, but it doesn't seem to work. Here is the asynctask code:

public class UploadAttachment extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        userRef.child("currentSeason").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.exists()) {

                    final String attachCurrentSeason = dataSnapshot.getValue().toString();

                    seasonRef.child("id").addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            String path = "users/" + mAuth.getUid() + "/" + attachCurrentSeason + "/game" + String.valueOf(Integer.parseInt(dataSnapshot.getValue().toString()) - 1);
                            StorageReference storageReference = storage.getReference(path);

                            storageReference.putBytes(byteArray);

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        return null;
    }
}

I've read many things saying that Asynctask will still run when the activity is destroyed, but it doesn't work for me. Is it not allowed to use firebase in asynctask?

Any help is appreciated. Thanks in advance!

As videos could be very heavy to send, I suggest you to use a Background Service, which you can find informations on the official Android documentation .

You can create it this way: (it is better to define a separate UploadVideoService.java class)

public class UploadVideoService extends IntentService {
    public UploadVideoService() {
        super("UploadVideoService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        String path = workIntent.getStringExtra("path");
        StorageReference storageReference = storage.getReference(path);
        storageReference.putBytes(workIntent.getByteArrayExtra("data"));
    }
}

In your Activity, start the service passing all data to it:

//...
userRef.child("currentSeason").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            final String attachCurrentSeason = dataSnapshot.getValue().toString();
            seasonRef.child("id").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String path = "users/" + mAuth.getUid() + "/" + attachCurrentSeason + "/game" + String.valueOf(Integer.parseInt(dataSnapshot.getValue().toString()) - 1);

                    // here you call the service, replace Activity with your Activity name
                    Intent mServiceIntent = new Intent(Activity.this, UploadVideoService.class);
                    mServiceIntent.putExtra("path", path);
                    mServiceIntent.putExtra("data", byteArray);
                    startService(mServiceIntent);

                }
                @Override
                public void onCancelled(DatabaseError databaseError) {}
            });
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
//...

You also have to define the service in your manifest, this way:

<service android:name=".UploadVideoService" android:exported="false"/>

After the upload is completed you could put a notification in the notification bar to tell the user the job is done, for example.

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