I want to check, my program is in background or not! my prgram have one package(all of my classes is in one package). I searched and finally i found this way. i write this code but when my program is in background, my code not run. why?
public class BackgroundCheck extends AsyncTask<Context,Void,Boolean>{
@Override
protected Boolean doInBackground(Context... arg0) {
// TODO Auto-generated method stub
Context context=arg0[0];
return isAppInBackground(context);
}
private boolean isAppInBackground(Context context){
ActivityManager activityManager=(ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcess=activityManager.getRunningAppProcesses();
if (appProcess==null)
return false;
final String packageName=context.getPackageName();
Log.e("packageName", packageName);
//Toast.makeText(context, "packageName="+packageName,Toast.LENGTH_LONG).show();
for(RunningAppProcessInfo processInfo:appProcess){
if((processInfo.importance==RunningAppProcessInfo.IMPORTANCE_BACKGROUND)&&( processInfo.processName.equals(packageName))){
Log.e("process", "in background");
Toast.makeText(context, "process in background", Toast.LENGTH_LONG).show();
Log.e("packagenmae", processInfo.processName);
return true;
}
}
return false;
}
}
and i add this code in this class but when my program in background, else if was run ! like always my program is in foreground ! what is problem??
if((processInfo.importance==RunningAppProcessInfo.IMPORTANCE_BACKGROUND)&&( processInfo.processName.equals(packageName))){
Log.e("process", "in background");
Toast.makeText(context, "process in background", Toast.LENGTH_LONG).show();
Log.e("packagenmae", processInfo.processName);
return true;
}
else if((processInfo.importance==RunningAppProcessInfo.IMPORTANCE_FORGROUND)&&( processInfo.processName.equals(packageName))){
Log.e("process","in forground");
return true;
}
Can i use another way that run in api 7+? That way should be reliable... Thanks for advise
If you want to know that your app is in background or not then you have to use Service for that
you should go with this:
http://www.vogella.com/articles/AndroidServices/article.html
Only one activity can run at a time. All others are suspended when another activity becomes active.
If you want code to run reliably in the background you would need to use a service.