上次写了Android上调用百度人脸识别接口
但是只写到获取JSON字符串,在log当中打印,没有更新UI界面
这次简单写一下Android在子线程当中更新UI界面(TextView、ImageView)
这次调用的本地服务器接口,将图片上传到服务器中,返回JSON解析后再展示
通过Message传递消息给Handler更新界面
MessgActivity
package ss.demo16;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.speech.tts.TextToSpeech.ERROR;
/*
*@Author:Swallow
*@Date:2018/01/12
*/
public class MessgActivity extends AppCompatActivity implements View.OnClickListener {
public Button addph, putmes;
public ImageView ivphoto;
public TextView tvnum;
public static final int SELECT_PHOTO = 2;
public String path = null;
private int num;
private Bitmap orc_bitmap;
private ListView showlv;
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(msg.what == 1){
Bitmap bitmap = (Bitmap)msg.obj;
ivphoto.setImageBitmap(bitmap);
}else if(msg.what == ERROR){
Toast.makeText(MessgActivity.this,"显示图片错误",Toast.LENGTH_SHORT).show();
}else if(msg.what == 2){
tvnum = (TextView)findViewById(R.id.tv_num) ;
tvnum.setText((String) msg.obj);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messg);
addph = (Button) findViewById(R.id.add_photo);
putmes = (Button) findViewById(R.id.b_check);
addph.setOnClickListener(this);
putmes.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//添加一张照片,获取照片路径显示到控件上面,并且把路径值传给接口
case R.id.add_photo:
//判断权限是否打开
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} *else {
openAlbum();//打开相册
}
break;
case R.id.b_check:
if(path!=null){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try{
File file = new File(path);
String result = UploadUtil.uploadImage(file, "服务器url");
Log.v("mes",result);
String objlist = JSONObject.parseObject(result).getString("obj");
String urlist = JSONObject.parseObject(objlist).getString("imageUrl");
String num = JSONObject.parseObject(objlist).getString("faceNum");
String url = JSONObject.parseObject(urlist).getString("outputImageUrl");
Log.v("mes",num);
Log.v("mes",url);
Message msg = new Message();
msg.what = 2;
msg.obj = num;
handler.sendMessage(msg);
//通过图片的url显示图片
URL imgurl = new URL(url);
conn = (HttpURLConnection)imgurl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
msg = new Message();
msg.what = 1;
msg.obj = bitmap;
handler.sendMessage(msg);
}else {
msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
conn.disconnect();
}
}).start();
}
break;
}
}
private void openAlbum () {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
//@TargetApi(Build.VERSION_CODES.KITKAT)
private void handleImgeOnKitKat (Intent data){
//String imagePath = null;
Uri uri = data.getData();
Log.d("uri=intent.getData :", "" + uri);
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri); //数据表里指定的行
Log.d("getDocumentId(uri) :", "" + docId);
Log.d("uri.getAuthority() :", "" + uri.getAuthority());
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
path = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
path = getImagePath(uri, null);
}
Log.v("path:", path);
displayImage(path);
}
/**
* 通过uri和selection来获取真实的图片路径,从相册获取图片时要用
*/
private String getImagePath (Uri uri, String selection){
//String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
//显示图片到控件上面
private void displayImage (String imagePath){
if (!TextUtils.isEmpty(imagePath)) {
orc_bitmap = BitmapFactory.decodeFile(imagePath);//获取图片
if (orc_bitmap != null) {
ivphoto = (ImageView) findViewById(R.id.imageView);
ivphoto.setImageBitmap(orc_bitmap);
}
} else {
Toast.makeText(this, "图片获取失败", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//打开相册后返回
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
//判断手机系统版本号
if (Build.VERSION.SDK_INT > 19) {
//4.4及以上系统使用这个方法处理图片
handleImgeOnKitKat(data);
}
}
break;
}
}
}
服务器获取图片的工具类UploadUtil
import android.util.Log;
import com.alibaba.fastjson.JSONObject;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000;//超时时间
private static final String CHARSET = "utf-8";//设置编码
/**
* android上传文件到服务器
*
* @param file 需要上传的文件
* @param RequestURL 请求的url
* @return 返回响应的内容
*/
public static String uploadImage (File file, String RequestURL) {
String result = "error";
String BOUNDARY = UUID.randomUUID().toString();//边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data";//内容类型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);//允许输入流
conn.setDoOutput(true);//允许输出流
conn.setUseCaches(false);//不允许使用缓存
conn.setRequestMethod("POST");//请求方式
conn.setRequestProperty("Charset", CHARSET);//设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
conn.connect();
if (file != null) {
//当文件不为空,把文件包装并且上传
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
/*
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
dos.writeBytes(PREFIX + BOUNDARY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + file.getName() + "\"" + LINE_END);
dos.writeBytes(LINE_END);
FileInputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
int res = conn.getResponseCode();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuilder sbs = new StringBuilder();
int ss;
while ((ss = input.read()) != -1) {
sbs.append((char) ss);
}
result = sbs.toString();
Log.i(TAG, "result------------------>>" + result);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String upImage(ArrayList files, String RequestURL){
String result = "error";
String BOUNDARY = UUID.randomUUID().toString();//边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data";
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);//允许输入流
conn.setDoOutput(true);//允许输出流
conn.setUseCaches(false);//不允许使用缓存
conn.setRequestMethod("POST");//请求方式
conn.setRequestProperty("Charset", CHARSET);//设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
conn.connect();
if (files != null) {
//当文件不为空,把文件包装并且上传
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int res = conn.getResponseCode();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuilder sbs = new StringBuilder();
int ss;
while ((ss = input.read()) != -1) {
sbs.append((char) ss);
}
result = sbs.toString();
Log.i(TAG, "result------------------>>" + result);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
贴下界面