Android 停止背景音乐 [英] Android Stop Background Music

查看:55
本文介绍了Android 停止背景音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑 - 找到了一个简单的 5-10 行解决方案!!!请参阅下面我自己的答案!!!耶!!!!!!!!!

EDIT - FOUND A EASY 5-10 LINE SOLUTION!!! See MY OWN ANSWER BELOW!!! YAY!!!!!!!!!

我已经搜索了 5 个小时,几十个 SO 帖子,没有答案,这似乎是最简单的明显该死的事情!!!

I've searched for 5 hours, dozens of SO posts, no answers, and this seems like the most simple obvious freaking thing!!!

EDIT-顺便说一句,这不是一个音乐播放器应用程序,只是一个查看图片和文本的应用程序,打开多个活动,如菜单和关于,查看不同类型的图片等.我只是想在看的时候播放一些简单的背景音乐通过图片和文字,为什么这么难?

EDIT- btw, this is NOT a music player app, just an app to view pics and text, opens multiple activities like menu and about, view diff types of pictures etc. I just want to play some simple background music while looking thru the pics and text, why is that so difficult?

另一个编辑-似乎主要问题确实是:为什么按下 HOME 按钮不调用 onPause 或 onStop ???"-所以我可以知道何时停止媒体播放器?还有我在市面上下载的游戏是怎么做到的???

another EDIT - it seems the main question really is: "WHY DOES PRESSING THE HOME BUTTON NOT CALL onPause or onStop ???" -so I can know when to stop the media player? and how do the games I download on the market accomplish this???

家庭活动开始

然后

媒体播放器启动:

player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true);
player.setVolume(100,100);
player.start();

在 onCreate 之外声明的玩家

Player declared outside of onCreate

MediaPlayer player;

当其他活动打开时,背景音乐不间断,这很好,这就是我想要的.

When other activities are opened, the background music continues uninterrupted, which is GOOD, that is what I want.

现在,当我完成我的 非常 简单的应用程序(仅在 diff 活动中显示一些图片和文本)时,我可以多次单击 BACK 以返回主页/原始活动,然后然后再退出"一次,或者,我只需按主页退出",因为我已经完成了这个应用程序,我不需要再听那个音乐了.

Now, when I am done with my very simple app (that just shows some pics and texts in diff activities), I either click BACK multiple times to get to the home/original activity, and then one more time to "exit", OR, I simply press home to "exit" because I'm DONE with this app and I do not need to hear that music anymore.

选项 1

onPause 覆盖中调用 player.stop();,这 不是 我想要的,因为当我离开时背景音乐停止其他活动(如菜单"和关于")的家庭活动,我也不希望在打开新活动时使用暂停和恢复,因为我不希望漂亮的背景音乐跳过"或被打断.

Call player.stop(); in an onPause override, this is not what I want because background music stops when I leave the home activity for other activities like 'menu' and 'about', I also do not what to use pause and resume when opening new activities because I do not want the pretty background music to 'skip' or be interrupted.

选项 2

@Override
    protected void onPause() {
        super.onPause();
        if (this.isFinishing()){
            player.stop();
        }
    }

这样更好,因为背景音乐不会在活动之间停止,当我从我的家庭活动中按 BACK 时,音乐停止,我可以继续安静地享受我的 android fun 手机,但是 问题是,当按下 HOME 按钮退出"我的应用程序时,讨厌的背景音乐一直在播放.

This is better because background music does not stop between activities, and when I press BACK from my home activity, the music stops, and I can continue to enjoy my android fun phone in peace and quiet, but the problem is, when pressing the HOME button to "exit" my app, that pesky background music keeps playing.

奇怪

@Override
protected void onStop() {
        super.onStop();
        if (this.isFinishing()){
            player.stop();
        }
    }

和 onPause 一样(我也理解实际的区别)

Does the same as onPause (and I do understand the actual differences)

编辑- player.stop(); 似乎也无关紧要高于或低于 super.onStop();但它影响了我看不到的东西,无论如何,仍然没有解决方案:(

EDIT- ALSO it doesn't seem to matter if player.stop(); is above or below super.onStop(); but it affecting something i cant see, either way, still no SOLUTION :(

呜呜呜

呜呜呜

编辑 - 另一个选项 - 但不起作用

EDIT- ANOTHER OPTION- BUT DOES NOT WORK

public void onUserLeaveHint() {
    player.stop();
    super.onUserLeaveHint();
}

这会在我按 HOME 时停止音乐,但在我开始新活动时也会停止 :(

this stops the music when i press HOME but it also stops it when i start new activities :(

编辑 - 一个非常常见的工作,我在多个地方看到过,但似乎很荒谬:

EDIT - A VERY COMMON WORK AROUND IVE SEEN MULTIPLE PLACES, but seems to ridiculous to have to do:

基本上记录已打开和关闭的活动数量(onResume 和 onPause 可能是最好的,但这点无关紧要),当计数达到 0 时,停止背景音乐.是的,这很简单,但为什么我必须以编程方式执行此操作,实际上这篇文章的最大问题是:

essentialy keep count of the number of activities that have been opened and closed (onResume and onPause would prob be best, but that points irrelevant) and when that count reaches 0, stop the background music. YES that is pretty simple, but why do I have to programmatically do this, actually the BIGGEST QUESTION FOR THIS POST IS:

将其放入 onDestroy 不是一个选项,因为 onDestroy 仅在系统内存不足时调用,或者您强制关闭应用程序,这是有据可查的.

To put it in onDestroy is not an option because onDestroy is only called when the system is low on memory, or you force close your app, and that is well documented.

覆盖 HOME 按钮也不是选项,因为我已经读过它不可能"并且我已经读过它非常不赞成",无论哪种方式我都在避免这种情况.

Overriding the HOME button also is no option as I have read it's "not possible" and I have read it's "extremely frowned upon", either way I'm avoiding that.

我不认为需要创建SERVICE,即使我这样做了,我什么时候停止服务,似乎我会遇到同样的问题

I don't see the need to create SERVICE, and even if I did, when would I stop the service, it seems I would have the same problem

现在让我大吃一惊的是,我从安卓市场下载的每一个游戏和每一个应用都有非常优美的背景音乐,当我按下BACK 或 HOME,因为我玩完了那个可爱的游戏音乐停止,而不是继续在后台播放.

NOW HERE IS THE THING that completely blows my mind, every game and every app I have downloaded from the android market has very beautiful background music, and when I press BACK or HOME because I am done playing that lovely game the music stops, not keeping playing in the background.

我非常沮丧,我觉得这是因为我觉得我错过了一些非常简单的东西,因为这是任何应用程序最基本的生命周期问题之一.

I am very frustrated, and I feel it's because I feel like I am missing something very simple, because this is one of the most basic lifecycle issues with any app.

我花了一个月的时间阅读 developer.android.com 的每一页,包括开发指南、教程、示例项目,并研究参考部分,以及 5 小时谷歌搜索该主题.

I spent a month reading every page of developer.android.com including the Dev Guide, the tutorials, sample projects, and researching the Reference section, as well as google-ing this topic for 5 hours.

我也不明白为什么 6 或 7 个 SO 线程与 exact 相同的问题,没有得到回答 没有,市场上每个可下载的应用程序都停止播放它音乐(除非它是背景音乐播放器),当您按 HOME 或 BACK 或任何退出"应用程序以在手机上执行其他操作时.

I also don't understand why the 6 or 7 SO threads with the exact same issue, have not been answered, every downloadable app on the market stops playing its music (unless its a background music player) when you press HOME or BACK or whatever to "exit" the app to go do something else on your phone.

我错过了什么?

推荐答案

今天很开心,还有头发 :)我已经测试过了,它可以工作!!!

I'm very happy today, and still have hair :) I've tested this and it works!!!

首先,将此添加到您的清单中:

First, add this to your Manifest:

<uses-permission android:name="android.permission.GET_TASKS"/>

其次,将此添加到您的Home/Main"活动/类中:

Second, add this to your 'Home/Main' Activity/Class:

  @Override
  protected void onPause() {
    if (this.isFinishing()){ //basically BACK was pressed from this activity
      player.stop();
      Toast.makeText(xYourClassNamex.this, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", Toast.LENGTH_SHORT).show();
    }
    Context context = getApplicationContext();
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    if (!taskInfo.isEmpty()) {
      ComponentName topActivity = taskInfo.get(0).topActivity; 
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        player.stop();
        Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show();
      }
      else {
        Toast.makeText(xYourClassNamex.this, "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", Toast.LENGTH_SHORT).show();
      }
    }
    super.onPause();
  }

显然将 xYourClassNamex 替换为您的班级名称 :)

And obviously replace xYourClassNamex with, well, Your Class Name :)

现在显然您不需要Toasts",但它会告诉您发生了什么.非常有趣的想法是,当您从 'Home/Main' 活动按 BACK 时,您显然会得到 2 个 Toast,您从您的 'HOME/MAIN' 活动中按回",而第二个 Toast 是您在您的应用程序中切换了活动".我相信我知道为什么会发生这种情况,但这没关系,因为我称之为player.stop();"从 2 个场景中,这意味着我的应用程序不再被使用".显然比player.stop();"做更多的工作如果你需要:)而且很明显你不需要你在你的应用程序中切换活动"的其他",因为没有理由停止/暂停"背景音乐,这是我需要的,但如果你新活动开始时确实需要做点什么,好吧:)

Now obviously you do not need the "Toasts" but it will tell you what is going on. The very intersting thind is when you press BACK from your 'Home/Main' activity, you obviously get 2 Toasts, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", and the 2nd Toast is "YOU SWITCHED ACTIVITIES WITHIN YOUR APP". I believe I know why this happens, but it doesn;t matter because I call "player.stop();" from the 2 scenarios that mean my app is no longer being 'used'. Obviously do more work than "player.stop();" if you need to :) And also obvious you dont need the "else" for "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", because there is no reason to "stop/pause" the background music, which is what i needed, but if you DO need to do something when new activities are started, well here you go :)

希望这有助于任何想知道用户何时离开/退出/完成"应用程序的人:)

Hope this helps anyone looking to know when the user "leaves/exits/is done with" the app :)

感谢所有评论帖子并帮助大家!!!耶!

THANKS FOR ALL OF THE COMMENTS POSTS AND HELP EVERYONE!!! YAY!

编辑-

这部分必须在每个活动的 onPause 中:

This part has to be in EVERY activity's onPause:

Context context = getApplicationContext();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        if (!taskInfo.isEmpty()) {
          ComponentName topActivity = taskInfo.get(0).topActivity; 
          if (!topActivity.getPackageName().equals(context.getPackageName())) {
            player.stop();
            Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show();
          }
        }

这样您就可以知道用户是否从任何活动中离开了您的应用.很高兴知道这一点:)

so you'll know if the user left your app from ANY of the activities. this is good to know :)

这篇关于Android 停止背景音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆