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));
正确的吗?