我想從我的活動中調用服務類的stopService()方法。 但我不知道如何從我的活動類訪問stopservice方法。 我有下面的代碼,但它不工作...........如何從調用活動類中調用服務類的stopservice()方法
這是主屏幕類:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
enablecheck = (CheckBox)findViewById(R.id.enablecheck);
enablecheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(enablecheck.isChecked()){
startService(new Intent(HomeScreen.this, AutoService.class));
}else
{
stopService(new Intent(HomeScreen.this, AutoService.class));
}
}
});
}
This is Service Class:
public class AutoService extends Service {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Auto Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer = new Timer();
timer.scheduleAtFixedRate(task = new TimerTask(){
public void run()
{
System.out.println("done");
}
}, delay, period);
}
@Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
任何建議非常可觀。 感謝和問候 明圖
相關http://stackoverflow.com/questions/5555765/stop-service-in-android – 2016-02-14 10:26:26