原因是在子线程中更新UI导致的。
看到一个不错的分析,Android子线程与更新UI问题的深入讲解,更新UI的方法Android在子线程中更新UI的方法汇总(共七种)
我用的方法:(一个向服务器上传图片和其他信息以及接收服务器返回数据的工具类)
package com.example.style_transfer.Http;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.style_transfer.Util.ImageUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ImageUpload {
/**
* The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running
* these examples, please request your own client ID! https://api.imgur.com/oauth2
*/
private static final String IMGUR_CLIENT_ID = "123";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
private static final OkHttpClient client = new OkHttpClient();
private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
public static void run(File f, final String style, ImageView imageView) throws Exception {
final File file=f;
new Thread() {
@Override
public void run() {
//子线程需要做的工作
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("style", style)
.addFormDataPart("file", UUID.randomUUID().toString()+".jpg",
RequestBody.create(MEDIA_TYPE_PNG, file))
.build();
Log.d("requestBody", requestBody.toString());
//设置为自己的ip地址
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("http://192.168.1.113:8090/upload")
.post(requestBody)
.build();
Log.d("request", request.toString());
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// 将服务器返回的图片的base64转为bitmap
Bitmap bitmap = ImageUtil.base64ToBitmap(response.body().string());
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}