等待活动在非活动课程中完成

时间:2014-12-29 11:17:15

标签: android android-intent android-activity

我的应用程序中有一个方法,它启动一个新的Activity来启动Camera Application。 Camera Application返回结果(拍摄或未拍摄的照片),并将此结果存储在Intent-Bundle中。

在原始方法中,我想读取此包,但由于活动尚未完成,因此无效。

如何在继续我的方法之前等待活动完成?

方法

@Override    
public boolean startChallenge(Context context) {
        Intent cam = new Intent(context, CameraIntent.class);
        cam.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(cam);

        Boolean done = cam.getExtras().get("done"); // << this fails obviously
}

活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);         
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, CAPTURE_IMAGE_CAPTURE_CODE);
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    intent = getIntent();
    if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
        if (resultCode == RESULT_OK) {
            intent.putExtra("done", true);  
        } else if (resultCode == RESULT_CANCELED) {
            intent.putExtra("done", false);     
        }
    }
    finish();
}

我想保留代码的结构,因为startChallenge()方法继承自超类(Challenge),startChallenge因类型而异(例如,你必须拍照,另一个是挑战挑战你必须回答什么,等等)。该方法在另一个活动中被调用,具体取决于挑战的类型。

1 个答案:

答案 0 :(得分:0)

startChallenge 应该有一个对Activity的引用,它希望结果能够调用startActivityForResult

方式

@Override    
public boolean startChallenge(Activity activityB) {// Activity B in which you are expecting this result back.
    Intent cam = new Intent(activityB, ActivityA.class);
    activityB.startActivityForResult(cam, REQUEST_CODE_OPEN_CAMERA);
}

活动A

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    intent = getIntent();
    if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
        if (resultCode == RESULT_OK) {
            intent.putExtra("done", true);  
        } else if (resultCode == RESULT_CANCELED) {
            intent.putExtra("done", false);     
        }
    }

    setResult(RESULT_OK, intent);
    finish();
}

另一种方法是使用LocalBroadcastManagerOtto

活动A

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
        if (resultCode == RESULT_OK) {
            BusProvider.getInstance().post(new ImageCapturedEvent(true));
        } else if (resultCode == RESULT_CANCELED) {
            BusProvider.getInstance().post(new ImageCapturedEvent(false));
        }
    }

    finish();
}