线程的挂起与唤醒之实现app加载广告点击跳转功能
在实现app添加启动广告轮换、点击跳转过程中碰到各种问题,有点击第一张图跳转后返回已经跑进主界面不显示其它广告图的情况(因为没有在跳转的时候把线程挂起),有点击广告跳转返回后不继续跳转到下一张广告图的情况(在onResume方法中没有调用notify()方法),也有点击最后一直广告图返回不了的情况(这个不知道什么原因,好像是因为把线程休眠写在后面导致的),最后参考网上的资料调试终于解决,实现功能。关于线程挂起与唤醒参考:
http://blog.sina.com.cn/s/blog_4c0706560101175r.html
,具体实现代码如下:
public class LogoActivity extends BaseActivity implements Runnable { int num = 0; boolean flag = true; Bitmap[] bitmaps; ImageView image; private boolean suspendFlag = false;// 控制线程的执行状态 String[] url = { "http://www.10010.com/goodsdetail/511405139289.html", "http://www.10010.com/tesla", "http://www.10010.com/goodsdetail/981410108357.html" }; int logoId[] = { R.drawable.logo1, R.drawable.logo2, R.drawable.logo3 }; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: image.setBackgroundResource(logoId[num]); break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.logo); Resources res = getResources(); bitmaps = new Bitmap[3]; for (int i = 0; i < bitmaps.length; i++) { bitmaps[i] = BitmapFactory.decodeResource(res, logoId[i]); } image = (ImageView) this.findViewById(R.id.logo); Thread thread = new Thread(this); thread.start(); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub link(url[num]); } }); } private void link(String str) { //调用浏览器加载广告页 // TODO Auto-generated method stub String adress = str; // web address Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(adress)); startActivity(intent); } @Override protected void onPause() { // TODO Auto-generated method stub suspend(); super.onPause(); } @Override protected void onResume() { // TODO Auto-generated method stub resume(); super.onResume(); } public void suspend() { //线程暂停 this.suspendFlag = true; } public synchronized void resume() { //唤醒线程 this.suspendFlag = false; this.notify(); } public void run() { // TODO Auto-generated method stub while (flag) { try { Thread.sleep(2000L); synchronized (this) { //同步代码块控制线程状态 while (suspendFlag) { wait(); } } if (num < bitmaps.length - 1) { num++; handler.sendEmptyMessage(1); } else { flag = false; Intent it = new Intent(LogoActivity.this, WelcomeActivity.class); startActivity(it); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); finish(); }}