简述,不得不说和这几个大神交涉,那简直就是勾心斗角,各种调试,还不是因为了解得太少了。不过不得不说,这个bitmap简直就是强大,runnable、handle也很实用,要不然,也不花这功夫了。好,入题;
1、需求:从网络请求图片成功后,将其设置为imageview的背景图;
2、代码:
//调用时,如此写:
new Thread(runnable).start();
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
Log.e(TAG, "handleMessage: "+msg.what );
switch (msg.what){
case CaptureCamera:
imgtest.setImageBitmap(bmp_title);
getCaptureCemera();
tv_test.setText("设置成功");
break;
private Runnable runnable=new Runnable() {
@Override
public void run() {
while (photoUrl=="") {
try {
photoUrl = MyApplaction.getOpenSDK().captureCamera("736175838", 1);//必须在子线程中获取
} catch (BaseException e) {
e.printStackTrace();
}
Log.e(TAG, "new thread,photoUrl: " + photoUrl);
}
if (photoUrl!=""){
final byte[] data=getImages(photoUrl);//子线程中执行
bmp_title=BitmapFactory.decodeByteArray(data,0,data.length);//子线程中执行
mHandler.sendEmptyMessage(CaptureCamera);//主线程中更新ui
}
}
};
//加载图片
private byte[] getImages(String path) {
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(6 * 1000);
InputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
}
return outputStream.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
外接sdk获取图片的地址必须在子线程中运行,所以在写在runnable中,并且在调用的时候如此写:new Thread(runnable).start();,这样才可以;文章中哪里该写在哪里的要求已经注明。
更多bitmap方法参考https://blog.youkuaiyun.com/zjws23786/article/details/79892150;