How to stop Android Service started with a custom intent - android

I built a class called MService extend Service in Android Studio , I started the service like this: - inside onClick associated with a button-
Intent serviceIntent = new Intent(getApplicationContext(), MService.class);
serviceIntent.putExtra("ID", "1");
startService(serviceIntent);
The Service onStartCommand method lunched and worked pretty good..
The problem is I don't know how to end the Service when a Button clicked, I tried to do this:
stopService(new Intent(getApplicationContext(), MService.class));
inside a onClick method , the onDestroy lunched, but the Service still running
How can I stop it?

inside a onClick method , the onDestroy lunched, but the Service still running
If onDestroy() of your service was called, then afterwards, the service is not running. Your code might still be running.
If you start things in a service, such as a background thread, it is your job to stop them and clean that up, typically in your onDestroy() method.

Related

Android app seems to be duplicating when I swipe it away and start it again

I am currently having a really weird issue, and I don't know what could be causing it. Every time I close the app by swiping it away, and then start it again, the app seems to be duplicating its output to logcat, or in other words, it appears to be running multiple times.
This doesn't happen when I am connected to Android Studio, but without a cable connection, it does it without fail.
In my main activity I start my service like this:
Intent intent = new Intent(this, BluetoothService.class);
startService(intent);
bindService(intent, bluetoothServiceConnection, Context.BIND_AUTO_CREATE);
Stopping the service:
unbindService(bluetoothServiceConnection);
Intent intent = new Intent(MainActivity.this, BluetoothService.class);
stopService(intent);
EDIT I have made some changes in the way I stop and start my service, which seems to have solved my problem on Android 5.1.1, but not on Android 4.4.4, sadly.
I was thinking that maybe my logging process could be the problem, but destroying that process in my activity's onDestroy()-method didn't solve the issue either.
Starting the logging process:
logger = Runtime.getRuntime().exec(new String[]{"logcat", "-v", "time", "-f", logcatFile.getAbsolutePath(), " *:E"});
Stopping it:
logger.destroy();
If you start a service, depends how you define your service in the AndroidManifest.xml, if you have android:process=":yourProcess", if the process name start with ":" it will create a new process, that probably your log output multiple times.
Your code doesn't contains any logging information, nor did you provide a stacktrace with it. Your splash screen doesn't seem to be the issue, but you should replace the new thread with a delayed post to a handler to the looper thread (main thread) you're running in:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
}, 1500);
Instead of getApplicationContext() you could also use SplashActivity.this directly.
In your MainActivity you then need to make sure to unbind the service. Maybe also stop it, depending on what you need it for. Refer to Bound Services for more documentation and examples.
For making the Service terminate the documentation states
A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated.
That's why it works when the service isn't started at all. You try to stop the service in onDestroy() which is only called if the service is stopped. Your code looks like the service doesn't need to be started at all. But to do it correctly, just stop the service in the acivity's onDestroy() or utilize
onUnbind() or any other useful lifecycle event of the activity or service.

How to Stop bind local intent service

I have made the Intent service and designed it in such a way that it has capability of restart itself if killed by the OS , but if it is stopped by user it must have stop.
Every thing was going good. But Problem occured when I tried to implement message handler and Binding techniques.
What I have done
My sole purpose was getting the status from the service (which in my case is intent service) and update my views. For this I have implemented Message handler and start to bound the service .
I am binding my service in such a way
//This is my interface to get specific call back in activity
mReceiver = new DownloadResultReceiver(new Handler());
mReceiver.setReceiver(ListSuitClass.this);
serviceIntent = new Intent(DownloadService.ALARM_SERVICE);
serviceIntent.setClass(ListClass.this, DownloadService.class);
serviceIntent.putExtra("receiver", mReceiver);
serviceIntent.putExtra("requestId", 101);
startService(serviceIntent);
}
if (!mIsBound) {
bindService(serviceIntent, mConnection, BIND_DEBUG_UNBIND);
mIsBound = true;
}
Problem
I want to stop the service by stop button , But it stop for a while and starts over again .
I do not know what I am doing wrong , And what is starting again the service.
Please help me in stopping the service.
Note: I am running my service in a separate process.
As per the code, mIsBound might be the local variable of Activity. When you stop your activity and restart it, it will have the default value of boolean i.e. false and so bindService is called again and again. What you need to do is either make it static variable or store the service bind status in SharedPreferences and read value from it.

Android start service issue in onCreate of Activity

I have tried to start a service and bind to the service in my Activity's onCreate() method. When I try to call a function from service like commSessionManagerService.startCommandUpperM() afterwards, a NullPointerException occurs. Here is the code that I use to start the service and bind to it:
Intent startIntent = new Intent(this, CommSessionManagerService.class);
startService(startIntent);
Intent bindIntent = new Intent(this, CommSessionManagerService.class);
bindService(bindIntent, conn, Context.BIND_AUTO_CREATE);
If I move the function startCommandUpperM() to onStartCommand() in the CommSessionManagerService, the onCreate method will take several seconds to complete. As a related note, I have a created and started a thread in the startCommandUpperM() function.
This is because your Service is actually bound on the UiThread. As onCreate also runs on UiThread, your call to bindService result in Handler.post(Runnable) be called on the main thread's handler.
So when bindService returns, the Service isn't already bound.
To circumvent this problem, you should put your code using your Service inside ServiceConnection.onServiceConnected().

Service not closed properly

I have an android application which starts a service in the main activity with this command:
bindService(new Intent(ctx, MyService.class), _connection, Context.BIND_AUTO_CREATE);
The main activty does excatly nothing with this service (thats why I didnĀ“t provide the code for the Service connection). The idea is that the main activity handels the service lifetime!
It "stops" the service with this code after the user clicks the "close" button of my app:
if (_service != null) {
unbindService(_connection);
}
//Some cleanup here ...
System.exit(0);
I know at this point that no other activity is binded to the service cause every activity is called from the main activity and they unbind from the service at "onStop".
So the problem is that my Service wont call "onDestroy" when the user closes the app!
When I remove the "System.exit(0)" line it will close normally!
How can I make sure that the service is closed properly in this situation?
EDIT:
Ok I read this discussion: Is quitting an application frowned upon?.
Now I rebuild my activities. I have one activity that calls the service with startService, after that it binds the service. When the activity is destroyed it calls unbindService.
The service itself returns START_STICKY in onStartCommand to make it harder to kill it. It calls stopSelf when all work is done.
Now I have the problem that I get the ServiceConnectionLeaked message if the binding still exists! Whats about that? How could I prevent this?
Use finish() instead of System.exit(0)

Service called several times ending itself

I am starting a service with a click on a button :
Intent intent = new Intent(getActivity(), UploadService.class);
getActivity().startService(intent);
My apps makes it possible to launch several services.
I know that the first time, onCreate() is called, then if the services is running, onStartCommand() is called.
onStartCommand returns START_STICKY.
But I'm facing a strange behavior :
On the first click, the Service is called, onCreate() then onStartCommand()... etc.
On the second click, while the Service is still running, onStartCommand()... etc.
But when the first is finished, onDestroy() is called, while the second is still in progress... ?
How to avoid that?
Thanks
If you start the Service that is already running then onDestroy() of Service won't be called and the instance of Service already running will be brought to front but if your Service is finished/stopped explicitly then only its onDestroy() will be called.

Categories

Resources