Android使用线程获取网络图片的方法
来源:爱站网时间:2021-01-07编辑:网友分享
如果Android应用程序中有一个直接获取图像的耗时操作,那么它可能会很耗时,如果你对Android使用线程获取网络图片的方法感兴趣,可以一起随爱站技术频道小编来看看吧,相信可以给大家带来一些参考。
如果Android应用程序中有一个直接获取图像的耗时操作,那么它可能会很耗时,如果你对Android使用线程获取网络图片的方法感兴趣,可以一起随爱站技术频道小编来看看吧,相信可以给大家带来一些参考。
AndroidManifest.xml
activity_main.xml
MainActivity.class
package com.zdcrobot.handlermessage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button button;
private ImageView imageView;
private String imagPath = "http://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
private final int IS_FINISH = 1;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Bitmap bitmap = (Bitmap)msg.obj;
imageView.setImageBitmap(bitmap);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
imageView = (ImageView)findViewById(R.id.image1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new MyClass()).start();
}
});
}
public class MyClass implements Runnable{
@Override
public void run() {
Bitmap bitmap = null;
try {
URL url = new URL(imagPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = Message.obtain();
message.obj = bitmap;
message.what = IS_FINISH;
handler.sendMessage(message);
}
}
}
以上就是爱站技术频道小编为大家带来的Android使用线程获取网络图片的方法,如果大家还有什么问题,可以多关注js.aizhan.com,或者直接登录我们爱站技术频道详细了解。
