简体   繁体   English

我怎么知道应用程序何时在后台?

[英]How do I know when application is in the background?

I have an application that is a menu with several options, every option when chosen will lead to a new activity. 我有一个应用程序,它是一个带有多个选项的菜单,选择每个选项都会导致新的活动。 I also have music playing in the background using a service. 我还使用服务在后台播放音乐。 I want my music play continuously no matter what activity is focused. 无论我专注什么活动,我都希望音乐能够连续播放。

My problem is: 我的问题是:

  • If I am NOT override onPause() or onStop(), the music will go fine when I open another activity. 如果我没有覆盖onPause()或onStop(),那么当我打开另一个活动时音乐将正常播放。 BUT when I press home button, music still plays. 但是,当我按下主屏幕按钮时,音乐仍会播放。
  • If I DO override onPause() or onStop(), the music will stop when I press Home button, but it also stops when another activity is opened. 如果我确实重写onPause()或onStop(),则当我按“主页”按钮时音乐将停止,但在打开另一个活动时也将停止音乐。

So what should I do now? 那我现在该怎么办?

You can override onPause() and use a boolean flag. 您可以重写onPause()并使用一个布尔标志。
Set the boolean to true if you are launching a new activity. 如果要启动新活动,请将布尔值设置为true When onPause() is called you'll know if it is not true then you should stop the music. 调用onPause() ,您会知道它是否为true然后应该停止播放音乐。

boolean keepPlaying = false;

protected void onPause() { 
    if(!keepPlaying)
        stopService(new Intent(this, MediaPlayerServices.class)); 
    super.onPause();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何知道应用程序在android中后台运行多长时间? - How do i know how long the application is running in background in android? 我怎么知道后台线程何时完成了 AsyncTask? - How do I know when the background thread is finished with AsyncTask? Android:如何知道哪些应用程序向前台打开并在后台运行时做些什么 - Android: How to know what application is opened to foreground and do something when it goes to background 我如何知道何时可以从后台线程安全地调用方法? - How do I know when a method can be called safely from a background thread? 我怎么知道我的Android应用程序实例不再存在? - How do i know when my android application instance no longer exists? 我如何知道我的Android应用程序是否在后台运行? - How do I know whether or not my Android app is running in background? 绘制视图时我怎么知道? - How do i know, when view is drawn? 我怎么知道何时刷新FirebaseInstanceId? - How do I know when the FirebaseInstanceId is refreshed? 当我减少它时,如何从我的离子应用程序顶部更改背景颜色? - How do I change the background color from the top of my ionic application when I reduce it? 当我发送新消息时,我怎么知道我的应用程序? - how to i know in my application, when i sent new message?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM