Reputation: 475
I'm developing an app that makes asynchronous calls to server for notifications. Everything works fine in the main activity. Now what's bothering me, that i need a service that would poll for notifications when the app is not active (just like GMail stock app). So I start remote service in another process in the main activities onStop function like that:
@Override
public void onStop() {
super.onStop();
if(prefs.getBoolean(OPTIONS_KEY_SERVICE, false)) {
startServiceIntent = new Intent(CloudAlarmsService.MY_SERVICE);
Bundle b = new Bundle();
b.putStringArray("duidCodes", duidCodes);
startServiceIntent.putExtras(b);
Log.d("SSE_SERVICE", "Starting Service");
startService(startServiceIntent);
}
}
It works fine, i get notifications after the activity was closed. Now i would like to stop remote service on activity start (so i won't have activity and service polling server concurrently). I do it like this:
@Override
public void onResume() {
super.onResume();
stopService(new Intent(CloudAlarmsService.MY_SERVICE));
Log.d("SSE_SERVICE", "Stopping service");
}
CloudAlarmsService.MY_SERVICE is a string in my service class:
public class CloudAlarmsService extends Service {
public static String MY_SERVICE = "cloudindustries.alarms.service.BACKGROUND_SERVICE";
...
and also it is declared in manifest xml like that:
<service android:process=":alarms_poller" android:name=".CloudAlarmsService">
<intent-filter android:label="@string/serviceStopService">
<action android:name="cloudindustries.alarms.service.BACKGROUND_SERVICE" />
</intent-filter>
</service>
But service is not stopped and it keeps working. After i close the main activity another instance of service spawns and continues polling.
Is there something i am missing out? Or maybe this is a bad use for a remote service or even there is another type of service / manager which could be used for such purpose?
Thanks for any help!
Edit:
Question clarification: Is it possible to stop remote service from different activity (which did not start the service)?
Upvotes: 3
Views: 5924
Reputation: 132982
try to stop CloudAlarmsService
service as:
Intent intent = new Intent();
intent.setClass(getApplicationContext(), CloudAlarmsService.class);
getApplicationContext().stopService(intent);
Upvotes: 0