Android: Stop / start service created in onCreate ()

I currently have a service that runs in the onCreate method for an action using:

Intent intentService = new Intent(this, MainService.class); this.startService(intentService); 

I now need to stop this service by pressing a button and restart it again by pressing another button, however I am not sure how to stop this service and start it again from the side of the onCreate method.

I think I will need to start the service in a different way than what I'm doing now? But I'm not sure about the best method for this.

I was looking at stopping the service in android , but their method of starting the service does not seem to work inside onCreate.

A more complete look at my code:

 public class MainActivity extends Activity { 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); Intent intentService = new Intent(this, MainService.class); this.startService(intentService); } private OnClickListener btn_lock = new OnClickListener() { public void onClick(View v) { unlock.setVisibility(View.VISIBLE); lock.setVisibility(View.GONE); } }; private OnClickListener btn_unlock = new OnClickListener() { public void onClick(View v) { unlock.setVisibility(View.GONE); lock.setVisibility(View.VISIBLE); } }; 
+7
source share
1 answer

When you want to start a service, you need

  startService(new Intent(this, MainService.class)); 

And to stop the service at any time, just call

 stopService(new Intent(this, MainService.class)); 

Remember that the service must be declared in AndroidManifest.xml. As you said, your service is running. I'm sure you did it. More AndroidManifest.xml

  <service android:enabled="true" android:name=".MainService" /> 
+23
source

All Articles