zoukankan      html  css  js  c++  java
  • android 图片查看器

    android实现的图片查看器

        public class MainActivity extends AppCompatActivity {
    
        private EditText et_new_path;
        private ImageView iv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
    
            et_new_path =(EditText)findViewById(R.id.et_new_path);
            iv = (ImageView) findViewById(R.id.iv);
        }
    
         public void click(View view)
        {
            new Thread(){//在android中一般获取一个子线程来实现一个费时的操作。如果不明白,下面有解释
                public void run(){
                    try
                    {
                        String path = et_new_path.getText().toString().trim()//获取输入框中的路径
            
                        URL url = new URL (path);
    
                        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    
                        conn.setRequestMethod("GET");
    
                        conn.setConnectTimeout(5000);
    
                        int code = conn.getResponseCode();
    
                        if(code == 200)
                        {
                            InputStream in = conn.getInputStream();
    
                            final Bitmap bitmap = BitmapFactory.decodeStream(in);
    
                            runOnUiThread(new Runnable(){
                            public void run(){
                                iv.setImageBitmap(bitmap);
                            }
                            });
                        }
                    }
                    catch(Exception e)//这里为为了方便这样写
                    {
                       e.printlStackTrace();
                    }
                }
            }.start();
        }
    }
    

    1.为什么要创建一个子线程呢?


    ####我个人最开始也是不明白其中的原因,于是从网上找一找解释。在android中的主线程的作用是负责控制UI Thread界面的显示、更新和控件交互。UI Thread所执行的内容花费的时间最好越短越好。而其他比较费时的工作(访问网络,下载数据,查询数据库等)都应该交給子线程执行,以免堵塞主线程。
    ####2.runOnUiThread的用法: 在开发文档中的写法是: Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread. ####上面的英文的大致含义是:运行一个指定的动作,若果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,行动是发布到UI线程的事件队列。

    3.使用Handler 与 使用runOnUiThread的区别:

    [1] 如果仅仅是更新一个UI则可以使用runOnUiThread来代替Handler

    [2] 但是需要携带多条数据的时候还是需要使用handler与Message

    最后别忘了加用户权限

    <uses-permission android:name="android.permission.INTERNET"/>
    
  • 相关阅读:
    xp sp3下 IIS5.1 配置python 的正确方法
    asp 采集不到数据,采集不成功 拒绝访问 msxml3.dll 错误 '80070005' 的解决方法
    列表样式
    css文本属性
    css背景属性
    常规流练习
    盒模型练习
    定位体系相关练习
    层叠机制的步骤
    简单网页的制作——html
  • 原文地址:https://www.cnblogs.com/gxcstyle/p/6807663.html
Copyright © 2011-2022 走看看