UI界面更新必须在ui线程中 不能在ruanable线程中操作ui 可以发送消息利用handler来更新ui
private void load() {
LoadDate load = new LoadDate();
load.execute("http://h.hiphotos.baidu.com/image/w%3D310/sign=1bc9c0da38292df597c3aa148c305ce2/c83d70cf3bc79f3d77fbe1c5b8a1cd11728b2928.jpg");
}
class LoadDate extends AsyncTask<String, Integer, Bitmap> {
@Override
protected void onPreExecute() {
// myDialog.setTitle("请稍候");
// myDialog.setMessage("loading......");
// myDialog.setCanceledOnTouchOutside(false);
// myDialog.show();
}
@Override
protected Bitmap doInBackground(String... params) {
URL myFileUrl = null;
Bitmap bitmap = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
myFileUrl = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection)myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
is =conn.getInputStream();
bitmap =BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(is != null){
is.close();
}
if( conn != null){
conn.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
startTime(bitmap);
return bitmap;
}
Handler myHandler=new Handler(){
public void handleMessage(Message msg) {
if(msg.what==1){
Toast.makeText(MainActivity.this, "连接服务器超时"+msg.obj, 1).show();
}
};
};
private void startTime( final Bitmap bm) {
Runnable run=new Runnable() {
boolean isRun=true;
long enableTime;
long startTime=System.currentTimeMillis();
@Override
public void run() {
System.out.println(bm+"---bm----");
while(isRun){
enableTime=System.currentTimeMillis()-startTime;
if(enableTime>=3000 &&bm==null){
Message message = new Message();
message.what = 1;
message.obj="demo";
myHandler.sendMessage(message);
// Toast.makeText(MainActivity.this, "连接服务器超时", 1).show();
isRun=false;
}
try{
Thread.sleep(50);
}catch (Exception e) {
System.out.println("计时器线程 sleep ex:"+e.toString());
}
}
System.out.println("计时器线程run..end time:"+enableTime);
}
};
// Looper.prepare();
new Thread(run).start();
}
@Override
protected void onPostExecute(Bitmap result) {
image.setImageBitmap(result);
// myDialog.cancel();
System.out.println(result+"---");
}
}
}
相关文章
- 09-18请求的Android权限未显示在应用权限设置中
- 09-18android – 请勿在主题中请求Window.FEATURE_ACTION_BAR并将windowActionBar设置为false以使用工具栏代替
- 09-18Android网络请求框架------Retrofit的使用
- 09-18httpclient: 设置请求的超时时间,连接超时时间等
- 09-18Android-OkHttp-使用TrafficStats标记所有网络请求
- 09-18Android RecycleView搜索列表内容(OkHttp网络请求)
- 09-18Okhttp使用简析——Android网络请求框架(一)
- 09-18istio设置请求超时
- 09-18HttpClient连接请求超时设置
- 09-18微信小程序的网络设置,及网络请求:wx.request(OBJECT)