Reputation: 161
Can finish() be used to close an activity from a service? If not, what is the proper way to end an activity from a Service? I've created an activity from my service and need to close it.
Upvotes: 1
Views: 424
Reputation: 1006604
Can finish() be used to close an activity from a service?
Not directly. The service really really really really should not have a reference to the activity on which to call finish()
.
I've created an activity from my service and need to close it.
Odds are, you should not be starting the activity from the service in the first place. Users will attack you with axes if they feel you are interrupting them unnecessarily.
If not, what is the proper way to end an activity from a Service?
Preferably, let the user close the activity. Those users who do not attack you with axes for interrupting them by popping up the activity will attack you with clubs for interrupting them by getting rid of the activity while they are using it.
Beyond that, use a Messenger
or something to send a message from the service to the activity, and let the activity handle that as desired in a Handler
, which could include calling finish()
.
Upvotes: 1
Reputation: 756
When possible I usually prefer the override option for closing activities:
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
And in the main activity:
@Override
public void onDestroy() {
super.onDestroy();
Log.d(logTag,"onDestroy");
}
How the activity can be started:
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
super.onStart(intent, startid);
}
Upvotes: 0