JavaHava
JavaHava

Reputation: 189

How to detect when someone leaves the application?

I have a button that plays a sound in my app. If the user leaves the screen and has the app running in the the background it still plays. How do I detect when the user is outside the app so that I can stop the sound from playing in the background?

Main Activity Code for current stop button within app

    stop_button = findViewById(R.id.stop_button);
    stop_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (longplay_button.isChecked() &&  meme_Sound_Media_Player.isPlaying()) {
                meme_Sound_Media_Player.pause();
                meme_Sound_Media_Player.seekTo(0);
                longplay_button.setEnabled(true);

            } else if (memeSoundMediaPlayer.isPlaying()) {
                memeSoundMediaPlayer.pause();
                memeSoundMediaPlayer.seekTo(0);
                longplay_button.setEnabled(true);
            }
            else {
                Toast.makeText(getBaseContext(), "nothing is playing", Toast.LENGTH_SHORT).show();
            }

            if (inactiveButton.isShown()) {
                inactiveButton.setImageResource(R.drawable.button_pressed);
                inactiveButton.setEnabled(true);
                Toast.makeText(getBaseContext(), "Playback Stopped", Toast.LENGTH_SHORT).show();


            }

        }
    });

}

Error 1

Error 1

Error 2

enter image description here

Current view enter image description here

Upvotes: 0

Views: 129

Answers (1)

ismail alaoui
ismail alaoui

Reputation: 6073

Pull this dependency in your build.gradle file:

   dependencies {
   implementation "android.arch.lifecycle:extensions:1.1.1"
  }

Then in your Application class, use this:

public class MyApplication extends Application implements LifecycleObserver {

@Override
public void onCreate() {
    super.onCreate();
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackgrounded() {
    Log.d("MyApp", "App in background");
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForegrounded() {
    Log.d("MyApp", "App in foreground");
}
}

Update your AndroidManifest.xml file:

<application
    android:name=".MyApplication"
    ....>
</application>

Upvotes: 1

Related Questions