Tôi đang cố gọi phương thức stopService() của lớp dịch vụ từ hoạt động của mình. Nhưng tôi không biết cách truy cập phương thức stopervice từ lớp hoạt động của mình. Tôi có đoạn code dưới đây nhưng nó không làm việc ...........Cách gọi phương thức stopervice() của lớp Dịch vụ từ lớp hoạt động gọi
Đây là màn hình chính lớp:
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);
}
}
Mọi đề xuất đều đánh giá cao. Cảm ơn và kính trọng Mintu
http://stackoverflow.com/questions/5555765/stop-service-in-android liên quan –