2013-02-05 99 views
6

我在服務中有一個線程,我希望能夠在我的主要活動類上按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));正確停止服務的方式嗎?

回答

9

無法停止,有一個運行勢不可擋循環這樣

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(); 

} 
+0

當我按下'buttonStop'並將其傳遞給服務器時,如何更改布爾變量? – TJ1

+0

你不需要這樣做,通過調用'stopService()','onDestroy()'的Service將被調用,然後設置布爾值將爲false – 2013-02-05 06:07:23

+0

其實我需要能夠停止我的代碼運行('我的代碼運行'),所以我需要能夠改變'運行'當我按下'buttonStop'。 – TJ1

-2

您調用onDestroy()方法停止服務。