安卓网络图片查看(WebView)

来源:互联网 发布:知乎 机敏级潜艇 编辑:程序博客网 时间:2024/05/16 05:23

安卓中实现在程序中打开网页需要借助WebView组件。

主要代码如下

<pre name="code" class="java">    <span style="FONT-WEIGHT: normal">public class MainActivity extends Activity {          private EditText imagepath;          private ImageView imageView;          @Override          public void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);              setContentView(R.layout.main);                            imagepath = (EditText) this.findViewById(R.id.imagepath);              imageView = (ImageView) this.findViewById(R.id.imageView);                            Button button = (Button) this.findViewById(R.id.button);              button.setOnClickListener(new View.OnClickListener() {                            public void onClick(View v) {                      String path = imagepath.getText().toString();                      try{                          byte[] data = ImageService.getImage(path);//获取图片数据                          if(data!=null){                              //构建位图对象                              Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);                              imageView.setImageBitmap(bitmap);//显示图片                          }else{                              Toast.makeText(getApplicationContext(), R.string.error, 1).show();                          }                                         }catch (Exception e) {                          Toast.makeText(getApplicationContext(), R.string.error, 1).show();                      }                  }              });          }      }</span>  [html] view plaincopy    <span style="FONT-WEIGHT: normal">public class ImageService {          /**           * 获取图片           * @param path 网络图片路径           * @return 图片的字节数据           */          public static byte[] getImage(String path) throws Exception{              URL url = new URL(path);              HttpURLConnection conn = (HttpURLConnection) url.openConnection();              //设置超时时间              conn.setConnectTimeout(5000);              conn.setRequestMethod("GET");              if(conn.getResponseCode()==200){                  InputStream inStream = conn.getInputStream();                  byte[] data = StreamTool.read(inStream);                  return data;              }              return null;          }      }</span>  


多线程是指程序中包含多个执行流,即在一个程序中可以同时运行多个不同的线程来执行不同的任务,也就是说允许单个程序创建多个并行执行的线程来完成各自的任务。

可以提高CPU的利用率。在多线程程序中,一个线程必须等待的时候,CPU可以运行其它的线程而不是等待,这样就大大提高了程序的效率。

该程序借助了线程的方法实现。

0 0
原创粉丝点击