Dev.Sinto
Dev.Sinto

Reputation: 6862

How to stop background music when application is not visible to the user

I need to play a continuous background music for application only when application is visible to the user.

It stops only when application is goes background or terminated.

How can I do that?

Upvotes: 2

Views: 2094

Answers (3)

farhad.kargaran
farhad.kargaran

Reputation: 2373

Using onPause() is not a good solution because when you open another activity the onPause() of previous activity will be called while your app is visible!

this is what you should do: Create an application class and override onTrimMemory() method:

public class App extends Application {

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { // Works for Activity
        //implement your code for stopping music
    }
    else if (level == ComponentCallbacks2.TRIM_MEMORY_COMPLETE) { // Works for FragmentActivty
         //implement your code for stopping music
    }
}
}

do not forget to define this class in Manifest.xml:

        android:name=".App" //add this line in application tag of Manifest file

Upvotes: 0

Zento
Zento

Reputation: 335

You can use the onPause()-Method of the Activity-Class to stop the background-music. When the app gets resumed you have start it again with onResume().

See: http://developer.android.com/reference/android/app/Activity.html#onPause%28%29

Upvotes: 1

HXCaine
HXCaine

Reputation: 4258

The onPause() method that you can override in your activity will be called when the application is removed from the user's view.

Place whatever code you need to stop the music within that method, and you can be sure it will be called when the user presses 'back' or 'home'.

See here for the activity lifecycle:

http://developer.android.com/reference/android/app/Activity.html

Upvotes: 2

Related Questions