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));
正確停止服務的方式嗎?
當我按下'buttonStop'並將其傳遞給服務器時,如何更改布爾變量? – TJ1
你不需要這樣做,通過調用'stopService()','onDestroy()'的Service將被調用,然後設置布爾值將爲false – 2013-02-05 06:07:23
其實我需要能夠停止我的代碼運行('我的代碼運行'),所以我需要能夠改變'運行'當我按下'buttonStop'。 – TJ1