获取线程导致Android的另一个活动

时间:2018-12-16 19:45:20

标签: android multithreading image-processing android-intent runnable

“我的主要活动”调用Future,同时调用ResultActivity线程。我希望Result活动不要等待可能稍后由线程提供的结果处理(图像)的某些部分,并且UI可能会相应地更新。

下面是我尝试做的事情。

MainActivity(以下方法实际上是另一个Runnable的{​​{1}}):

callback

结果图像处理器:

thread

结果活动:

@Override
public void onCreate(Context context) {
    resultImageProcessor = new ResultImageProcessor();
    resImgProThread = new Thread(resultImageProcessor);
}

@Override
public void onBarcodeDetected(final Barcode barcode) {
    resultImageProcessor.setCameraBarcode(mCameraSource,barcode);
    resImgProThread.start();

    Intent intent = new Intent(this, ResultActivity.class);
    intent.putExtra(BarcodeObject, barcode);
    intent.putExtra(ResultCode, CommonStatusCodes.SUCCESS);
    intent.putExtra(ResImgProcObject, resultImageProcessor);
    startActivity(intent);
}

使用以上代码,在调用public class ResultImageProcessor implements Serializable, Runnable { private ResultActivity resultActivityContext; ResultImageProcessor(){ this.resultActivityContext = null; } public void setResultActivity(ResultActivity resultActivity) { this.resultActivityContext = resultActivity; } public void setCameraBarcode(CameraSource cameraSource, Barcode barCode){ mCameraSource = cameraSource; barcode = barCode; } @Override public void run() { String picPath = ProcessImage(Obj..Attributes); //wait until result activity context is not set while(resultActivityContext == null){ try { sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } resultActivityContext.onImageSaved(picPath); } } 之后,结果活动将不会启动,也不会运行runnable的protected void onCreate(Bundle savedInstanceState) { //... data = getIntent(); Barcode barcode = data.getParcelableExtra(MainActivity.BarcodeObject); ResultImageProcessor resultImageProcessor = data.getParcelableExtra(MainActivity.ResImgProcObject); resultImageProcessor.setResultActivity(this); } //called from Result image processor public void onImageSaved(String imagePath){ ImageView barImgView = findViewById(R.id.barcode_image); Bitmap barcodeImage = BitmapFactory.decodeFile(imagePath); barImgView.setImageBitmap(barcodeImage); barImgView.invalidate(); } 方法在while循环中。我使用记录器跟踪了它们。当我跳过线程并将图像路径传递给活动时,除了进行活动切换的速度很慢之外,其他一切都很好。

请指出问题或提出更好的解决方案。

2 个答案:

答案 0 :(得分:1)

我认为您缺少这样的可运行对象

@Scope(value = "prototype", proxyMode =
ScopedProxyMode.NO)

答案 1 :(得分:1)

事实证明,问题在于将ResultImageProcessor对象作为 Parcelable 传递给ResultActivity意图。我遵循了一条简单的方法,在resultActivityContext中将ResultImageProcessor声明为静态。

public class ResultImageProcessor implements Runnable {
    public static ResultActivity resultActivityContext;
    ...
    @Override
    public void run() {
        ...
        resultActivityContext.onImageSaved(picPath);
        resultActivityContext = null;
    }
}

和ResultActivity中的

ResultImageProcessor.resultActivityContext = this;