——>这是主方法的代码实现
public class MainActivity extends AppCompatActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
}
//Button监听
public void onPlay(View v){
//图片的路径
onTask("http://img.juhe.cn/cookbook/s/1/45_0824e37faf00b71e.jpg");
}
//具体实现
public void onTask(String path){
//创建接口帮助类 并调用接口
MyAsynct myAsynct = new MyAsynct(new MyAsynct.Info() {
@Override
public void onBitmap(Bitmap bitmap) {
//判断一下是否有传图片过来
if (bitmap != null){
//重新赋值
img.setImageBitmap(bitmap);
}
}
});
//
myAsynct.execute(path);
}
}
-------->一个帮助类 主要实现的是AsyncTask
public class MyAsynct extends AsyncTask<String,Void,Bitmap> {
//Bitmap 图片专用
//接口回调
private Info info;
public interface Info{
void onBitmap (Bitmap bitmap);
}
//构造方法
public MyAsynct(Info info){
this.info = info;
}
@Override
protected Bitmap doInBackground(String... params) {
String path = params[0];
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int code = connection.getResponseCode();
if (code == 200){
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);//解码流
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null){//判断是否有没有值
info.onBitmap(bitmap);
}
}
}
-------->XML文件
<Button
android:onClick="onPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="加载图片" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:id="@+id/img"/>