我目前有一个应用程序,当按下按钮时会启动服务并在服务内创建一个线程。然后我有第二个按钮(一旦按下第一个按钮就会出现)应该关闭服务并反过来杀死线程,下面是我当前的代码但是服务似乎停止但线程继续运行。
public class MainActivity extends Activity {
private static Button lock = null;
private static Button unlock = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock = (Button) this.findViewById(R.id.lock);
unlock = (Button) this.findViewById(R.id.unlock);
lock.setOnClickListener(btn_lock);
unlock.setOnClickListener(btn_unlock);
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
text.setVisibility(View.GONE);
startService(new Intent(this, MainService.class));
}
private OnClickListener btn_lock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
startService(new Intent(MainActivity.this, MainService.class));
}
};
private OnClickListener btn_unlock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.GONE);
lock.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, MainService.class));
}
};
}
然后我的服务类看起来像:
public class MainService extends Service {
Thread 1Thread;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while(true){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TEST", "Thread is still here!");
}
}
};
}
@Override
public void onDestroy() {
1Thread.interrupt();
}
@Override
public void onStart(Intent intent, int startId) {
1Thread.start();
}
}
希望有人可以提供帮助,如果您需要更多信息,请告诉我!