embedded linux ,android

2010年11月18日 星期四

android thread




ThreadDemo .java
package wandroide.blogspot.com;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadDemo extends Activity 
{
    ProgressBar bar1 = null;
    ProgressBar bar2 = null;
    TextView    tv   = null;

    Handler handler=new Handler(){
 @Override
 public void handleMessage(Message msg) 
 {
     bar1.incrementProgressBy(5);
 }
    };

    Handler handler2=new Handler(){
 @Override
 public void handleMessage(Message msg) 
 {
     bar2.incrementProgressBy(-5);
 }
    };
   
    AtomicBoolean isRunning=new AtomicBoolean(false);
    AtomicBoolean isRunning2=new AtomicBoolean(false);

    @Override
    public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv   = (TextView)findViewById(R.id.tv);
  bar1 = (ProgressBar)findViewById(R.id.progressbar1);
  bar2 = (ProgressBar)findViewById(R.id.progressbar2);
    }

    public void onStart() 
    {
 super.onStart();
 bar1.setProgress(0);
 bar2.setProgress(100);
     
 Thread background=new Thread(new Runnable() 
 {
      public void run() 
      {
          try {
              for (int i=0;i<20 && isRunning.get();i++) 
              {
                  Thread.sleep(1000);
                  handler.sendMessage(handler.obtainMessage());
              }
          }
          catch (Throwable t) {
               // just end the background thread
          }
       }
  });
      
  Thread background2=new Thread(new Runnable() 
  {
      public void run() 
      {
          try {
              for (int i=0;i<20 && isRunning2.get();i++) 
              {
                  Thread.sleep(1000);
                  handler2.sendMessage(handler2.obtainMessage());
              }
          }
          catch (Throwable t) {
              // just end the background thread
          }
      }
   });

   isRunning.set(true);
   background.start();
       
   isRunning2.set(true);
   background2.start();
    }

    public void onStop() {
  super.onStop();
  isRunning.set(false);
  isRunning2.set(false);
    }
}

沒有留言:

張貼留言