1.申请Internet权限,在AndroidManifest.xml文件中添加如下权限
<uses-permission android:name="android.permission.INTERNET"/>
2.注意加载网络图片操作不能放在主线程中进行,由于加载网络图片需要一定的耗时,建议配合Handler使用。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImg = (ImageView)findViewById(R.id.img);
new Thread(new Runnable() {
@Override
public void run() {
bm = getURLimage("http://image.sinajs.cn/newchart/daily/n/sh601006.gif");
Message msg = new Message();
msg.what = 1;
mHandler.sendMessage(msg);
}
}).start();
}
在子线程中进行获取,得到bitmap对象后,通过handler通知主线程刷新UI。
private Handler mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
mImg.setImageBitmap(bm);
break;
}
}
};
3.解决异常点:java.io.IOException: Cleartext HTTP traffic to image.sinajs.cn not permitted
2021-08-10 10:57:04.402 22288-22322/? W/System.err: java.io.IOException: Cleartext HTTP traffic to image.sinajs.cn not permitted
2021-08-10 10:57:04.402 22288-22322/? W/System.err: at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
2021-08-10 10:57:04.402 22288-22322/? W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
2021-08-10 10:57:04.402 22288-22322/? W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
2021-08-10 10:57:04.403 22288-22322/? W/System.err: at com.example.myapplication.MainActivity.getURLimage(MainActivity.java:75)
2021-08-10 10:57:04.403 22288-22322/? W/System.err: at com.example.myapplication.MainActivity$1.run(MainActivity.java:38)
2021-08-10 10:57:04.403 22288-22322/? W/System.err: at java.lang.Thread.run(Thread.java:923)
图片依然没有成功加载,查看日志打印,发现如上错误。
解决方案:
在AndroidManifest.xml中application的节点添加属性:
android:usesCleartextTraffic="true"
关于此异常出现的原因和其他解决方案,可以参考:https://blog.csdn.net/gengkui9897/article/details/82863966
|