开发者

How to stop service by itself?

I start a service in an a开发者_StackOverflow中文版ctivity then I want the service to stop itself after a while.

I called stopSelf() in the service but it doesn't work.

How to make the service stop itself?


By saying "doesn't work", I guess you mean that the onDestroy()-method of the service is not invoked.

I had the same problem, because I bound some ServiceConnection to the Service itself using the flag BIND_AUTO_CREATE. This causes the service to be kept alive until every connection is unbound.

Once I change to use no flag (zero), I had no problem killing the service by itself (stopSelf()).

Example code:

final Context appContext = context.getApplicationContext();
final Intent intent = new Intent(appContext, MusicService.class);
appContext.startService(intent);
ServiceConnection connection = new ServiceConnection() {
  // ...
};
appContext.bindService(intent, connection, 0);

Killing the service (not process):

this.stopSelf();

Hope that helped.


By calling stopSelf(), the service stops.

Please make sure that no thread is running in the background which makes you feel that the service hasn't stopped.

Add print statements within your thread.

Hope this helps.


since you didnt publish your code, i cant know exactly what you are doing, but you must declare WHAT you are stopping:

this.stopSelf();

as in:

public class BatchUploadGpsData extends Service {
    @Override
    public void onCreate() {
        Log.d("testingStopSelf", "here i am, rockin like a hurricane.   onCreate service");
        this.stopSelf();
    }


If by "doesn't work" you mean the process doesn't get killed, then that's how android works. The System.exit(0) or Process.killProcess(Process.myPid()) will kill your process. But that's not the Android way of doing things.

HTH


   stopForeground(true);
            stopSelf();


To let your service to stop itself.. create a BroadcastReceiver class.. In your service call your receiver like this..

In service

sendBroadcast(new Intent("MyReceiver"));

In Broadcast Receiver

 public class MyReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

         context.stopService(new Intent(context,NotificationService.class));
     }
 }

Manifest file

    <receiver
        android:name="MyReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="MyReceiver"/>
        </intent-filter>
    </receiver>


Use stopSelf() to stop a service from itself.


I know this is an old question, but in my case (floating window as service) I had to remove the view first, and then call stopSelf().

windowManager.removeView(floatingView);
stopSelf();


I just ran into the same issue. In my case, I have a singleton service manager that I use to communicate with the service. In the manager the service is started like this:

context.bindService(new Intent(context, MyService.class), serviceConnection, Context.BIND_AUTO_CREATE); 

By removing Context.BIND_AUTO_CREATE as suggested by Alik Elzin, I've been able to stop the service using this.stopSelf() and to have onDestroy() called when doing so. This problem is that after that I wasn't able to restart the service from the manager using the command above.

Finally I've fixed this by using a callback from the service that tells the manager to stop the service. This way the manager is always in charge when it comes to start/stop the service and everything seems to work fine. I don't know if there are any counter indications in doing it this way.

The code is really simple. Create a callback in the service and set it in the manager like this in your connection class:

private ServiceConnection mServiceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        myService = ((MyService.LocalBinder)service).getService();

        myService.setCallback(new MyService.MyServiceCallback() {
            @Override
            public void onStop() {
                stopService();
            }
        });
    }

    public void onServiceDisconnected(ComponentName className) {
        myService = null;
    }
};

and stop service:

public void stopService()
{
    if(mServiceConnection != null){
        try {
            mContext.unbindService(mServiceConnection);
        } catch (Exception e) {}
    }

     mContext.stopService(new Intent(mContext, BleDiscoveryService.class));
}

In the service, simply call myCallback.onStop() when you need to stop it.


Another dirty hack not mentioned here is to throw an exception like NPE. One day I needed to stop InputMethodService and this hack was useful.


if you use separate Thread in your service, after stopping service by calling stopSelf() or stopService() the Thread keeps running. if u want to stop Thread u should call Thread.interrupted() in the Thread(it might cause an Exception if Thread is already sleeping)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜