zoukankan      html  css  js  c++  java
  • AsyncTask 不能与Thread.sleep()同时使用解决方案

    public class MainActivity extends Activity {
    
    	private ImageView iv_ads;
    	String urrstrString = "http://a.hiphotos.baidu.com/image/pic/item/7af40ad162d9f2d3f7ec95eeabec8a136327cc36.jpg";
    	Bitmap bitmap;
    	ProgressDialog pDialog;
    
    	private Handler handler = new Handler();
    	private Runnable runnable = new Runnable() {
    		@Override
    		public void run() {
    			try {
    				Thread.currentThread();
    				Thread.sleep(10000);
    				startActivity(new Intent(MainActivity.this, NextActivity.class));
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	};
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		requestWindowFeature(Window.FEATURE_NO_TITLE);
    		setContentView(R.layout.activity_main);
    		iv_ads = (ImageView) findViewById(R.id.iv_ads);
    		new LoadImage().execute(urrstrString);
    
    		iv_ads.setOnClickListener(new OnClickListener() {
    
    			@Override
    			public void onClick(View v) {
    				MainActivity.this.startActivity(new Intent(MainActivity.this,
    						AdsActivity.class));
    			}
    		});
    
    	}
    
    	private class LoadImage extends AsyncTask<String, String, Bitmap> {
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    			pDialog = new ProgressDialog(MainActivity.this);
    			pDialog.setMessage("Loading Image ....");
    			pDialog.show();
    		}
    
    		protected Bitmap doInBackground(String... args) {
    			try {
    				bitmap = BitmapFactory.decodeStream((InputStream) new URL(
    						urrstrString).getContent());
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			return bitmap;
    		}
    
    		protected void onPostExecute(Bitmap image) {
    			if (image != null) {
    				iv_ads.setImageBitmap(image);
    				pDialog.dismiss();
    				handler.postDelayed(runnable, 4000);
    			} else {
    				pDialog.dismiss();
    				Toast.makeText(MainActivity.this,
    						"Image Does Not exist or Network Error",
    						Toast.LENGTH_SHORT).show();
    			}
    
    		}
    
    	}
    }
    

      异步线程与直接在oncreate() 中Thread.sleep()达不到预期的停留几秒的效果,可以用Handler发送消息,来实现效果...............

  • 相关阅读:
    String的转换问题
    springmvc maven搭建一
    top 使用心得
    spring 之AOP 和继承方法
    xml语法
    tomcat 相关
    json之注意
    javaScript 中创建json/转换字符串为json
    java基础之继承
    vim复制,删除
  • 原文地址:https://www.cnblogs.com/spring87/p/4347201.html
Copyright © 2011-2022 走看看