当有人使用我的Android应用程序将视频上传到Firebase存储时,即使活动被销毁,我也希望上传视频。我尝试使用asynctask,但它似乎不起作用。这是asynctask代码:
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;
}
}
我已经阅读了许多内容,说Asynctask仍会在活动被销毁时运行,但它对我不起作用。不允许在asynctask中使用firebase吗?
感谢任何帮助。提前谢谢!
答案 0 :(得分:1)
由于发送的视频非常繁重,我建议您使用后台服务,您可以在official Android documentation找到信息。
您可以这样创建:(最好定义一个单独的UploadVideoService.java类)
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"));
}
}
在您的活动中,启动服务将所有数据传递给它:
//...
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) {}
});
//...
您还必须以这种方式在清单中定义服务:
<service android:name=".UploadVideoService" android:exported="false"/>
上传完成后,您可以在通知栏中发出通知,告诉用户作业已完成,例如。