Background music Android

后端 未结 9 1527
夕颜
夕颜 2020-12-03 01:57

Okey, this is my problem. I have one service class where Ive managed to create media player to play music in background all time. Here is code:

package com.t         


        
9条回答
  •  北海茫月
    2020-12-03 02:43

    Try following to stop the background music at HOME or BACK press.

    @Override
    protected void onStop() {
        super.onStop();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List services = activityManager
                .getRunningTasks(Integer.MAX_VALUE);
        boolean isActivityFound = false;
    
        if (services.get(0).topActivity.getPackageName().toString()
                .equalsIgnoreCase(getPackageName().toString())) {
            isActivityFound = true; // Activity belongs to your app is in foreground.
        }
    
        if (!isActivityFound) {
            if (player != null && player.isPlaying()) {
                player.release();
            }
        }
    }
    

提交回复
热议问题