how to keep mediaplayer playing through all activities - android

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

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

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.

Related

How to rebind to foreground service?

A foreground service is started and immediately bound to. Is there a way to know whether the serivce has been stopped or is still running after an activity restart. The safe way would be to execute startService anyway, but is there a cleaner one?
You can use this method from:
https://stackoverflow.com/a/6452570/5457878
To check if your service is still running. You can call this method in your onResume() or onCreate(), and if it is not running, I would restart it.
private boolean isServiceRunning(String serviceName){
boolean serviceRunning = false;
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
while (i.hasNext()) {
ActivityManager.RunningServiceInfo runningServiceInfo = i
.next();
if(runningServiceInfo.service.getClassName().equals(serviceName)){
serviceRunning = true;
if(runningServiceInfo.foreground)
{
//service run in foreground
}
}
}
return serviceRunning;
}

Android - How to check my app is open when receive a push-notification?

I need best solution. When I received a push notification, I want to know if my app is open or not, because if my application is open when the user onClick the notification I want to call specific method, but if the application is close I want to open the application.
Basically what you need is way to check if one of your activity is in Foreground. May be you should check this How to determine if one of my activities is in the foreground
//Use this method to check your app is running or not
public boolean isAppRunning(){
String packageName="Your package name";
ActivityManager activityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
List<ActivityManager.RunningAppProcessInfo> procInfoslist = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfoslist.size(); i++)
{
if(procInfoslist.get(i).processName.equals(packageName))
{
return true;
}
}
return false;
}
`
//Use this method to check any activity is running or not
public boolean isActivityRunning(Context ctx) {
ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
return true;
}
return false;
}

Check application is minimized/background

I am so surprised!
Because not able identify application currently in foreground or background,
when i pressed home button and my application is not in foreground. then after i have used to check application running in foreground or not.
public boolean isAppOnForeground()
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) { return false; }
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses)
{
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; }
}
return false;
}
it will returns always true even if my application actually not in foreground.
Note:
My application have 2 services,
1 service will be canceled when application is removed from recent task list( that i have achieved.)
2 service will be canceled when application goes in background. (that is check wifi signal strength.)
how to know app is foreground or background?
how to stop service when application is not in foreground?
Rely on Activity callback methods, such as onPause(), onStop() and onResume(), that will give you hints on the current state of Activity. The Activity reference gives a very broad explanation of every of those methods.
try handling onpause() event of activity class. Onpause is called when activity goes out of focus.

How to check if an activity is running in background/foreground from a service?

I have created a service which starts from an activity's onCreate and stops on the activity's onDestroy method. Now I have to check from a method of the service that whether the activity is running in foreground/background(for some cases like application is forcefully closed). How can I do that?
I need to do this coz as far I know there is no guarantee of calling onDestroy method of an activity if any the application is forcefully closed or any kind of crash. So, my service which starts when my activity launches won't stop after any crash or any forceful closing event.
I have seen this link where foreground activities can be checked. But I need to check a running activity in whatever state (either foreground or background)
Final Update
To check for all activities:
#Override
protected void onStop() {
super.onStop();
if (AppConstants.isAppSentToBackground(getApplicationContext())) {
// Do what ever you want after app close simply Close session
}
}
Method to check our app is running or not:
public static boolean isAppSentToBackground(final Context context) {
try {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground
// task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity
.getPackageName();// get the top fore ground activity
PackageManager pm = context.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo
.loadLabel(pm).toString();
// Log.e("", foregroundTaskAppName +"----------"+
// foregroundTaskPackageName);
if (!foregroundTaskAppName.equals("Your App name")) {
return true;
}
} catch (Exception e) {
Log.e("isAppSentToBackground", "" + e);
}
return false;
}
Answer updated again
Use the below method with your package name.It will return true if any of your activity is in foreground.
public boolean isForeground(String myPackage){
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) return true;
return false;
}
Answer Updated
Check this link first Checking if an Android application is running in the background
http://developer.android.com/guide/topics/fundamentals.html#lcycles is a description of the Life Cycle of an android application.
The method onPause() gets called when the activity goes into the background. So you can deactivate the update notifications in this method.
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
add permisions in the menifest as well
<uses-permission android:name="android.permission.GET_TASKS" />
Unfortunately, getRunningTasks() has been deprecated since Android API 21 (Android Lollipop):
This method was deprecated in API level 21. As of LOLLIPOP, this
method is no longer available to third party applications: the
introduction of document-centric recents means it can leak person
information to the caller. For backwards compatibility, it will still
return a small subset of its data: at least the caller's own tasks,
and possibly some other tasks such as home that are known to not be
sensitive.
Try this method to check your app is in background or not:
public boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
check this link & especially check the Answer Which shows this part of code
public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
Hope this help you.

Service getting called multiple times?

I am developing an application where I am running some background operations and displaying notification to the user when certain condition meets .When the user clicks on the notification it should take him to the main activity , with out restarting the service .
My problem is when I am clicking the notification it takes me to the main activity and starting my service again.I dont want to restart my service again .How can I achieve this .
I have used the following code to check weather a service running or not lease look at it
public static boolean isServiceRunning(String serviceName,Context context){
boolean serviceRunning = false;
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
while (i.hasNext()) {
ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) i
.next();
if(runningServiceInfo.service.getClassName().equals(serviceName)){
serviceRunning = true;
}
}
return serviceRunning;
}
I have used this piece of code and it's working fine :)
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (MyService.class.getName().equals(service.service.getClassName()))
{
found = true;
}
}
you could check getIntent() on the activity and put some extra on the intent bundle of the notification that you check to start or not the service.
Note:
if a service is already running, it is not restarted.
Finally I have rectified my code.as follows
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.sevicedemosolution.Myservice".equals(service.service.getClassName().toString())) {
return true;
}
}
return false;
}

Categories

Resources