Tôi có một sợi bên trong một dịch vụ và tôi muốn có thể dừng chỉ khi tôi nhấn buttonStop
trên lớp hoạt động chính của mình.Dừng một sợi bên trong một dịch vụ
Trong lớp hoạt động chính của tôi, tôi có:
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;
}
}
}
Và trong lớp dịch vụ của tôi, tôi có:
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();
}
}
cách tốt nhất để ngăn chặn sự mythread
là gì?
Cũng là cách tôi đã ngừng dịch vụ theo số stopService(new Intent(this, MyService.class));
chính xác?
làm cách nào để thay đổi biến boolean khi tôi nhấn nút 'buttonStop' và chuyển nó vào dịch vụ? – TJ1
Bạn không cần phải làm điều đó, bằng cách gọi 'stopService()', 'onDestroy()' của Dịch vụ sẽ được gọi sau đó, đặt boolean sẽ là false –
Thực ra tôi cần phải có thể dừng mã mà tôi đang chạy ('MÃ MY TO RUN'), vì vậy tôi cần có thể thay đổi' chạy' khi tôi nhấn 'nútStop'. – TJ1