0

I have a Service which is playing music. I've implemented fade out like this:

@Override
public void onDestroy(){
    volume=1.0f;
    fade_handler.post(fade_out);
    super.onDestroy();  
}

This is fade_out Runnable:

private Runnable fade_out = new Runnable(){
    public void run(){
        player.setVolume(volume, volume);
        if(volume>0.0f){
            volume-=0.05f;
            fade_handler.postDelayed(fade_out, 200);
        }
        else{
            player.stop();
            player.release();
            stopForeground(true);
            //here should be super.onDestroy()!!!!!!!
        }
    }
};

The problem is that now super.onDestroy() get's called before fade_out finishes - so I want to call super.onDestroy() inside this runnable - but how?

Community
  • 1
  • 1
c0dehunter
  • 6,412
  • 16
  • 77
  • 139

2 Answers2

2

It is not the best idea to do things like this in onDestroy() because this method is supposed to do cleanup. I suggest you doing the following:

  • Create a method like void fadeOutAndStop().
  • Set it to post a Runnable which fades out the volume and the calls stopSelf() (or the method you use to stop the service now).
  • Use the fadeOutAndStop() method when you need to stop your service.

This way you won't even need to do anything special in onDestroy(), and the design will be much cleaner.

Malcolm
  • 41,014
  • 11
  • 68
  • 91
  • Thank you, this indeed seems to be a better solution. One thing though - how do I call this function from my activity? Using [AIDL](http://developer.android.com/guide/developing/tools/aidl.html)? All I did before was stopService(intent). – c0dehunter Feb 09 '12 at 09:48
  • I think I found the answer. I need to bind the service. – c0dehunter Feb 09 '12 at 09:58
  • @PrimožKralj No, no, AIDL is an overkill. All you need is a [Binder](http://developer.android.com/guide/topics/fundamentals/bound-services.html#Binder) unless you're doing some interprocess communication or multithreading. – Malcolm Feb 09 '12 at 10:00
  • Ah, spasiba ;) One more short question: if I use bindService(...) in my Activity, is it ok if I stop the service with stopSelf() or should I also somehow unbind it in Activity afterwards? – c0dehunter Feb 09 '12 at 10:44
  • @PrimožKralj Нет проблем! `stopSelf()` is absolutely okay to use regardless of whether you bind to your service or not. In fact, if you use `startService(Intent)`, it is even required to stop the service explicitly. – Malcolm Feb 09 '12 at 12:29
1

The correct syntax would be YourServiceClassName.super.onDestroy(), but as Malcolm points out it's not a good idea.

Rob Pridham
  • 4,780
  • 1
  • 26
  • 38