Reputation: 519
I'm creating a face detection app and to decrease the workload on the main thread I'm using a background thread. The code is given below.
Thread background = new Thread(new Runnable() {
public void run() {
Log.d ("Thread", "Thread has started");
for (Feature feat : mClassifierFiles.keySet()) {
mFaces.put(feat, cvHaarDetectObjects(grayImage, mClassifiers.get(feat), mStorages.get(feat), 1.1, 3,
CV_HAAR_DO_CANNY_PRUNING));
if (mFaces.get(feat).total() > 0) {
Size previewSize = camera.getParameters().getPreviewSize();
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);
byte[] jdata = baos.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
saveImg(bmp);
}
postInvalidate();
opencv_core.cvClearMemStorage(mStorages.get(feat));
}
}
});
background.start ();
Now, I understand that the saving image part should be done in the main thread. Now what I don't get is, how to send the 'bitmap bmp' to the main thread?
Upvotes: 2
Views: 1415
Reputation: 651
The recommended way is to use an AsyncTask. It allows you to do some work in a background thread and then get the result on the main thread. Look it up and it will be obvious how to use it.
By the way, I don't see why you should do the saving of the bitmap on the main thread. That's a slow operation and should also be done in the background thread. Only displaying the image (or other UI interactions) should be done the main thread.
Upvotes: 2
Reputation: 1893
Either define a BroadcastReceiver
and send an Intent
from your worker thread, since Bitmap
is Parcelable
. You can also use startIntent if you want to launch a new activity to handle the bitmap, thus you won't need to define a BroadcastReceiver. Or define an Handler
in your main thread, pass it to your worker thread and then post a Runnable
to be executed on the main thread. You can also use runOnUiThread()
.
Upvotes: 1