android 运用AsyncTask 获取图片并显示
2016-05-07 00:13
471 查看
为什么BitmapFactory.decodeByteArray()返回null问题
activity_main.xml布局里面一个按钮跟一个imageView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="从网络上下载一张图片" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY"/> </LinearLayout>
MainActivity.java代码如下
import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.StringBuilderPrinter; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { private Button bt; private ImageView img; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.button); img = (ImageView) findViewById(R.id.imageView); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("提示信息"); progressDialog.setMessage("正在下载"); progressDialog.setCancelable(false); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MyAscyTask().execute(); } }); } public class MyAscyTask extends AsyncTask<String, Integer, byte[]> { @Override protected byte[] doInBackground(String... params) { InputStream ism = null; HttpURLConnection con = null; BufferedReader read = null; try { URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setReadTimeout(10000); con.setConnectTimeout(100000); ism = con.getInputStream(); read = new BufferedReader(new InputStreamReader(ism)); StringBuffer sb = new StringBuffer(); String line = null; while ((line = read.readLine()) != null) { sb.append(line); } return sb.toString().getBytes(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (ism != null) { ism.close(); ism = null; } if (read != null) { read.close(); read = null; } } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(byte[] bytes) { super.onPostExecute(bytes); Log.i("TAG", "onPostExecute: "+bytes.length+"==="+bytes[0]); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); img.setImageBitmap(bitmap); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } } }
运行结果: 记得运行时加权限,因为访问网络,不会从网络得到图片,因为BitmapFactory.decodeByteArray方法返回空
修改MainActivity.java
import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.StringBuilderPrinter; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { private Button bt; private ImageView img; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.button); img = (ImageView) findViewById(R.id.imageView); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("提示信息"); progressDialog.setMessage("正在下载"); progressDialog.setCancelable(false); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MyAscyTask().execute(); } }); } public class MyAscyTask extends AsyncTask<String, Integer, byte[]> { @Override protected byte[] doInBackground(String... params) { InputStream ism = null; HttpURLConnection con = null; ByteArrayOutputStream out=new ByteArrayOutputStream(); try { URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setReadTimeout(10000); con.setConnectTimeout(100000); ism = con.getInputStream(); int size; while ((size=ism.read())!=-1) { out.write(size); } return out.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (ism != null) { ism.close(); ism = null; } if (out!= null) { out.close(); out=null; } } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(byte[] bytes) { super.onPostExecute(bytes); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); img.setImageBitmap(bitmap); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } } }
运行结果:
总结:源码decodeByteArray方法的参数的说明
/** * Decode an immutable bitmap from the specified byte array. * * @param data byte array of compressed image data * @param offset offset into imageData for where the decoder should begin * parsing. * @param length the number of bytes, beginning at offset, to parse * @return The decoded bitmap, or null if the image could not be decoded. */ public static Bitmap decodeByteArray(byte[] data, int offset, int length) { return decodeByteArray(data, offset, length, null); }
再次修改MainActivity,实现边下载有进度条显示
import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.StringBuilderPrinter; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { private Button bt; private ImageView img; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.button); img = (ImageView) findViewById(R.id.imageView); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("提示信息"); progressDialog.setMessage("正在下载"); progressDialog.setCancelable(false); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MyAscyTask().execute(); } }); } public class MyAscyTask extends AsyncTask<String, Integer, byte[]> { @Override protected byte[] doInBackground(String... params) { InputStream ism = null; HttpURLConnection con = null; ByteArrayOutputStream out=new ByteArrayOutputStream(); try { URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setReadTimeout(10000); con.setConnectTimeout(10000); ism = con.getInputStream(); byte[] data = new byte[1024]; int size; long file_length=con.getContentLength(); long total_length=0; int i=0; while ((size=ism.read(data))!=-1) { out.write(data,0,size); total_length+=size; int progress=(int)((total_length/(float)file_length) * 100); Log.i("TAG", "doInBackground: "+total_length+"==="+file_length+ "==="+progress); Thread.sleep(500); publishProgress(progress); } return out.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (ism != null) { ism.close(); ism = null; } if (out!= null) { out.close(); out=null; } } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(byte[] bytes) { super.onPostExecute(bytes); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); img.setImageBitmap(bitmap); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); Log.i("TAG", "onProgressUpdate:....... "+values[0]); progressDialog.setProgress(values[0]); } } }
相关文章推荐
- 使用AlarmManager实现Android应用每天定时执行任务
- Android的jni或者是ndk的创建步骤
- windows 7 下安装 Android 设备驱动
- Android平台和java平台 DES加密解密互通程序及其不能互通的原因
- 不要使用Android Studio的Git Commit了---->记一次debug
- Android实现手势控制
- SystemService
- File
- Android 关于EditText文字的显示问题 和属性
- Android简单的自定义抽屉布局(DrawerLayout)
- Android MVP 详解
- Android的手势
- Android开发中,那些让你相见恨晚的方法、类或接口
- Android View绘制13问13答
- (转)Android 内存泄漏案例和解析
- Android中的Binder(二)
- Android之十SlidingMenu侧滑菜单的实现分析
- ActiveAndroid:活性记录的风格ORM(对象关系映射)
- Android OpenGL10 输入响应 <6>
- Android中pendingIntent的深入理解