I am trying to call my service class's stopService() method from my activity. But I dont know how to access stopservice method from my activity class. I have the below code but its not working...........
This is HomeScreen class:
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); } }
Any suggestion highly appreciable. Thanks and Regards Mintu
To start the service, call startService(intent) and to stop the service, call stopService(intent) .
The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is complete by calling stopSelf() , or another component can stop it by calling stopService() .
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
In fact to stopping the service we must use the method stopService()
and you are doing in right way:
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class); startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class); stopService(myService);
if you call stopService()
, then the method onDestroy()
in the service is called (NOT the stopService()
method):
@Override public void onDestroy() { timer.cancel(); task.cancel(); Log.i(TAG, "onCreate() , service stopped..."); }
you must implement the onDestroy()
method!.
Here is a complete example including how to start/stop the service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With