如何检测有人何时离开应用程序?

时间:2019-06-13 16:26:11

标签: android android-lifecycle

我有一个在我的应用中播放声音的按钮。如果用户离开屏幕并在后台运行应用程序,则仍会播放。如何检测用户何时不在应用程序之外,以便可以阻止声音在后台播放?

应用中当前停止按钮的主要活动代码

    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();


            }

        }
    });

}

错误1

Error 1

错误2

enter image description here

当前视图 enter image description here

1 个答案:

答案 0 :(得分:0)

将此依赖项拉到build.gradle文件中:

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

然后在您的Application类中,使用此:

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");
}
}

更新您的AndroidManifest.xml文件:

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