停止服务中的线程

时间:2013-02-05 05:44:20

标签: android multithreading service

我在服务中有一个线程,当我在主活动类上按buttonStop时,我希望能够停止该线程。

在我的主要活动课中,我有:

public class MainActivity extends Activity implements OnClickListener { 
  ...
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
         startService(new Intent(this, MyService.class));
         break;
    case R.id.buttonStop:
         stopService(new Intent(this, MyService.class));
         break; 
    }           
  }
}

在我的服务类中,我有:

public class MyService extends Service {
  ... 
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

 @Override
 public void onCreate() {
    int icon = R.drawable.myicon;
    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,  notificationIntent, 0);
    notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);     
    startForeground(ONGOING_NOTIFICATION, notification);
            ...
 } 

 @Override
 public void onStart(Intent intent, int startid) {
   Thread mythread= new Thread() { 
   @Override
   public void run() {
     while(true) {
               MY CODE TO RUN;
             }
     }
   }
 };
 mythread.start();
}

}

停止mythread的最佳方式是什么?

我通过stopService(new Intent(this, MyService.class));正确停止服务的方式也是正确的吗?

2 个答案:

答案 0 :(得分:8)

您无法阻止具有此类

运行不可阻挡循环的线程
while(true)
{

}

要停止该线程,请声明boolean变量并在while循环条件下使用它。

public class MyService extends Service {
      ... 
      private Thread mythread;
      private boolean running;



     @Override
     public void onDestroy()
     {
         running = false;
         super.onDestroy();
     }

     @Override
     public void onStart(Intent intent, int startid) {

         running = true;
       mythread = new Thread() { 
       @Override
       public void run() {
         while(running) {
                   MY CODE TO RUN;
                 }
         }
       };
     };
     mythread.start();

}

答案 1 :(得分:-1)

您调用onDestroy()方法停止服务。