java - 先等待方法完成,然后再继续运行

标签 java android-studio android-asynctask

我正在尝试运行一个名为 uploadProfilePhoto() 的方法,但即使 uploadProfilePhoto() 尚未完成运行,该方法调用后的代码也会先运行。无论如何,我可以让 uploadProfilePhoto() 在继续之前先完成它的过程吗?

我尝试使用 AsynTask 但它仍然不起作用。似乎是因为 doInBackground() 是针对一系列代码,而不是方法。

异步任务

protected class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        uploadProfilePhoto();
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        Toast.makeText(ProfileSetup.this, "Account created successfully.", Toast.LENGTH_SHORT).show();
        mAuth.signInWithEmailAndPassword(email, password);
        startActivity(new Intent(ProfileSetup.this, MainActivity.class));
    }
}

uploadProfilePhoto()

private void uploadProfilePhoto() {

    if (mImageUri != null) {
        final StorageReference imageReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));

        storageTask = imageReference.putFile(mImageUri);
        storageTask.continueWithTask(new Continuation() {
            @Override
            public Task<Uri> then(@NonNull Task task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }
                return imageReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    myUrl = downloadUri.toString();

                    String myid = getIntent().getStringExtra("uid");

                    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(myid);
                    reference.child("profilePicUrl").setValue(myUrl);
                    finish();
                } else {
                    Toast.makeText(ProfileSetup.this, "Failed", Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(ProfileSetup.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    } else {
        Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show();
    }
}

最佳答案

我可以想到两种方法

 storageTask = imageReference.putFile(mImageUri);
    storageTask.addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                myUrl = task.getResult().toString();
                String myid = getIntent().getStringExtra("uid");
                DatabaseReference reference = 
                FirebaseDatabase.getInstance().getReference("Users").child(myid);
                reference.child("profilePicUrl").setValue(myUrl);
                startActivity(new Intent(ProfileSetup.this, MainActivity.class));
                finish();
            } else {
                Toast.makeText(ProfileSetup.this, "Failed", 
                Toast.LENGTH_SHORT).show();
            }
        }

第二种方法实际上不是很干净和漂亮,应该被认为是一种不好的做法,但是了解替代方法并没有什么坏处,所以

你可以在说出imageReference.putFlie(mImageUri);之后立即启动MainActivity;

imgeReference.putFile(mImageUri);
startActivity(new Intent(ProfileSetup.this, MainActivity.class));

现在在MainActivity中

while(ProfileSetup.getImageUrl() == null){ // define a method to return the url
       Systemclock.sleep(500);            // if it is small image you can hote it will be uplaoded in seconds      
}
Picasso.with(this).load(ProfileSetup.getImageUrl()).fit().into(imageView); // the while loop terminates when your image gets uploaded because getImageUrl() did not return null , now you know image is there you can download and set it to imageView by using Piccaso 

使用这种方法,您不需要完整的监听器,但我不建议这样做,因为它更复杂并且不会处理任何 imageUploading 失败

关于java - 先等待方法完成,然后再继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824279/

相关文章:

java - 在 Grails 2.4 中使用 HTTPClient

java - 在java中输出一个正方形到控制台

java - Spring Security LDAP 身份验证并从本地数据库收集用户详细信息

android - android gradle plugin 3.0.0-alpha1版本太旧

java - 在 Android Studio 中获取 json 数据的问题

java - Android asynctask 像 arargs 方法一样只能重写或被其他 varargs 方法重写

java - Java 中的函数类似于 C 中的 printf

按下按钮后 Android 模拟器不断崩溃

java - 将游标与 AsyncTask 一起使用

java - AsyncTask 传递一个数组给 onProgressUpdate()