android 图片查看器

时间:2023-01-27 18:55:39

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"/>