• 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发送消息,来实现效果...............

  • 相关阅读:
    SpringBoot多数据库连接(mysql+oracle)
    SOAP与REST API的区别
    我与OAuth 2.0那点荒唐的小秘密
    我与Git的那些破事(下)--分支模型
    我与Git的那些破事(上)--代码管理
    Salesforce学习之路(十三)Aura案例实战分析
    Salesforce学习之路(十二)Aura组件表达式
    react 脚手架初次npm start时候运行报错
    兼容ie 提示用户升级浏览器 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    一行代码实现网站一键变灰功能
  • 原文地址:https://www.cnblogs.com/spring87/p/4347201.html
Copyright © 2020-2023  润新知