如何在ActivityResult上启动AsyncTask并在MainActivity上显示

时间:2013-05-17 10:33:34

标签: android android-intent android-asynctask main-activity

我打开了捕获图像的意图,OnActivityResult我调用AsyncTask开始对图像进行一些处理。问题是我想首先加载mainActivity,然后启动AsyncTask以查看AsyncTask的百分比。我怎么能这样做?

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
           try {
             rotationIfNeeded();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.v(TAG, "C");

            retrievePreferences();
            OcrAsyncTask aTask = new OcrAsyncTask(dialog, languageCode, languagePath, bitmap);
            aTask.execute(languagePath);

            while (aTask.doInBackground(languagePath)){
                //Do Nothing
            }

            recognizedText = aTask.getRecognizedText();
            Log.v(TAG, "The Recognized Text is = " + aTask.getRecognizedText());
            if ( recognizedText.length() != 0 ) {
                ocrResult.setText(ocrResult.getText().toString().length() == 0 ? recognizedText : ocrResult.getText() + " " + recognizedText);
                ocrResult.setSelection(ocrResult.getText().toString().length());
            }

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
        } else {
            Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在MainActivity中有这个

private class MyAsyn extends AsyncTask<Boolean, Void, Object> {
    private ProgressDialog pd;

    /** application context. */
    public MyAsyn(Activity activity) {
        pd = new ProgressDialog(activity);
    }

    protected void onPreExecute() {
        pd.setMessage("Loading.. Please wait");
        pd.show();
    }

    @Override
    protected String doInBackground(Boolean... urls) {

        pd.show();

        // do what you want to do in back ground

        return null;
    }

            @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
                    // code to notify the progress
    }

    @Override
    protected void onPostExecute(Object result) {
        pd.dismiss();
    }
}
在OnActivityResult方法中添加此

MyAsyn task = new MyAsyn(MainActivity.this);
task.execute(true);

等等返回活动结果,您的处理在后台启动