Android Stop Background Music

前端 未结 9 976
生来不讨喜
生来不讨喜 2020-12-01 02:29

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

I\'ve searched for 5 hours, dozens of SO posts, no answers, and this seems like t

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 02:50

    private static HashMap focus = new HashMap();
    
    public static void check(Context context, boolean hasFocus)
    {
        handler.removeMessages(0);
        focus.put(((Activity)context).getLocalClassName(), hasFocus);
        handler.sendEmptyMessageDelayed(0, 500);
    }
    
    public static void check(String classname, boolean hasFocus)
    {
        handler.removeMessages(0);
        focus.put(classname, hasFocus);
        handler.sendEmptyMessageDelayed(0, 500);
    }
    
    private static Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Iterator it = focus.values().iterator();
            while(it.hasNext())
            {
                if(it.next())
                    return;
            }
            pause();
            super.handleMessage(msg);
        }
    };
    

    this is an manager class methods.

    each activity implementing like after code

    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        MusicManager.check(this, hasFocus);
        super.onWindowFocusChanged(hasFocus);
    }
    

    I'm using this code with my game which is published and working great.

    What part of this code is terrible? and where's better solution? I want to know if exist.

    Mike, you answered to me my answer is terrible and not working, What's wrong with this?

提交回复
热议问题