[解决了UI线程的问题]
我想在后台线程中拍照,然后将其发送到服务器,之后我想从服务器接收响应
问题是拍照部分是好的,发送到服务器也很好,但接收响应不起作用。有什么想法吗?
答案 0 :(得分:0)
您无法从后台线程更新UI(视图)(在本例中为doInBackground),
覆盖onPostExecute并调用此capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 400, 400));
class TakePhotoTask extends AsyncTask<byte[], String, Bitmap> {
@Override
protected Void doInBackground(byte[]... data) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data[0], 0, data.length);
if (bitmap == null) {
//Toast.makeText(MainActivity.this, "Captured image is empty", Toast.LENGTH_LONG).show();
return null;
}
//capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 400, 400));
try {
Bitmap bmp = ((BitmapDrawable) capturedImageHolder.getDrawable()).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] array = bos.toByteArray();
final String tmp = Base64.encodeToString(array, Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 400, 400));
}
}
答案 1 :(得分:0)
您需要在onPostExecute
回调方法中放置访问UI元素的代码。但由于您还需要访问Bitmap
对象,因此我建议您更改AsyncTask
类定义,以包含Bitmap
作为第三个参数。
class TakePhotoTask extends AsyncTask<byte[], String, Bitmap> {
@Override
protected Bitmap doInBackground(byte[]... data) {
//since we want to decode the entire byte-array and not just 0th byte
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (bitmap == null) {
return null;
}
//the rest of your code/logic goes here...
return bitmap;
}
然后在你的后执行方法中:
protected void onPostExecute(Bitmap bitmap) {
if(bitmap == null ){return; }
capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 400, 400));
try {
//I am not sure what the purpose of this section of the code is...
//so I just left it here
Bitmap bmp = ((BitmapDrawable) capturedImageHolder.getDrawable()).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] array = bos.toByteArray();
final String tmp = Base64.encodeToString(array, Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
showDialog("Image Taken ?");
}
我希望这会有所帮助。