How can I stop my Service in another Activity?
I start the service in my summaryActivity
SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);
startService(SocketServiceIntent);
And start my statusActivity from my summaryActivity
Intent intent = new Intent(SummaryActivity.this,
StatusActivity.class);
intent.putExtra("MessageParcelable", mp);
startActivity(intent);
My problem is that I don't know how I can give my Statusactivity the SocketServiceIntent.
Just call the
stopService()
MethodYou should call
Activity(ContextWrapper)#stopService
:just call stopService in summaryActivity
You haven't explained how you're currently trying to use stopService() and what error you are getting. Expand your question a bit and you might get more helpful responses.
You need to call this from your activity:
Replace "SummaryActivity" with the name of the Activity class you are stopping the service from.
Make sure you have unbound the service from all binding activities before attempting to stop it. As the Android docs explain, you cannot stop a Service that is currently bound to an activity.
As a design tip: It's often better to call
stopSelf()
from within the running Service rather than usingstopService()
directly. You can add ashutdown()
method into your AIDL interface, which allows an Activity to request astopSelf()
be called. This encapsulates the stopping logic and gives you the opportunity to control the state of your Service when it is stopped, similar to how you would handle aThread
.For example:
This is particularly relevant since your Intent name suggests you might be dealing with network sockets. You will want to ensure you have properly closed your socket connections before your Service is stopped.
Start the service:
Stop the service in any activity: