Snake
Snake

Reputation: 14648

how to keep mediaplayer playing through all activities

I have an android app that has mutliple activities The first main activity starts background music using media player. How can I make this music continue playing while the app is im forground I tried to stop the app on the onpause method and starts it on the onresume method but its cumbersome to have the same code in every activity Thanks a lot

Upvotes: 0

Views: 1922

Answers (2)

Shraddha
Shraddha

Reputation: 1052

You cannot stop the Media Player in onPause if you want it to play untill the Application is in foreground. The reason is If you transit from Activity A to Activity B, the onPause of Activity A and onResume/onCreate of Activity B will be called. To achieve the things you want to implement, you will need to check when the application goes in the background. To do so, use the following functions :

public boolean isAppOnForeground(final Context context)
    {
        final ActivityManager activityManager = (ActivityManager)     context.getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null)
    {
        return false;
    }
    final String packageName = context.getPackageName();
    for (final RunningAppProcessInfo appProcess : appProcesses)
    {
        if ((appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) && appProcess.processName.equals(packageName))
        {
            return true;
        }
    }
    return false;
}

And for Background :

public static boolean isApplicationBroughtToBackground(final Context context)
{
        final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty())
    {
        final ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName()))
        {
            return true;
        }
    }
    return false;
}

To call this functions, Create a Base Activity and override their onPause() and onResume() method, Extend the Base Activity in place of Activity.

Hope this helps you.

Shraddha

Upvotes: 2

Tschegewara
Tschegewara

Reputation: 169

you should bind the mediaplayer to a sevice once its created! You can check on andriod developers page for services: http://developer.android.com/reference/android/app/Service.html

Once the mediaplayer is bound to the service it does not matter which activity is active.

Upvotes: 1

Related Questions