repeatedly checking whether the application is in foreground or background - android

I want to detect when the app comes from back ground to foreground every time.
I'm geting the state using the following code
topActivity.getPackageName().equals(context.getPackageName())
But I need to execute the code repeatedly so that I could detect every time when my app comes to foreground

It's your app. Activity always knows if it is visible or not. So make every your activity tell someone it's state. You don't need to poll app state. Check this answer.

Try this :
public static String 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";
}
Hope this helps.

Related

How to execute some event if RN has been killed?

Not sure if I understand correctly but according to this link
Deliver silent notifications and wake up your app in the background on the user's device.
It sounded to me that it's possible to perform some action even if the app has been killed.
Currently I'm using OneSignal as below:
OneSignal.addEventListener('received', this.onReceived);
onReceived(store, notification) {
store.dispatch(receivedNotification({ notification }));
}
However the above will only be able to dispatch action if the app is in background or foreground, but once the app been killed, despite receiving notification successfully, onReceived event will not be fired.
So my question is whether is it possible to "wake" my RN app in the background and dispatch a redux action?
There is no event that you can catch before app is killed. You also cannot prevent the user from killing your app. And once it is killed you cannot 'wake' it up, as your code is not running. You can only do such tasks when the app is in the background/foreground.
Yes, it is possible you can execute some event if RN has been killed.
now the question is how basically I am also using react-native and I have got some challenges also, I also want to execute some event if RN has been killed, but I did not get any answer actually my concern is to open an app which can and show a call screen when calling notification is received so I dig a lot and I found a solution,
first I created a bridge connection between javascript to java and then write a wakeful service which gets called every time when we receive notification and then I call my background intent service and in this service I wake up my activity and set some flags which help me to open screen when screen is lock depends on the conditions
// receiver Service //
public class MessagingService extends WakefulBroadcastReceiver {
private static final String TAG = "FirebaseService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, String.valueOf(!isAppOnForeground(context)));
if (intent.getExtras() != null) {
if (!isAppOnForeground((context))) {
//This get called every time you receive notification
}
}
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}

How to know when I close my app?

My question is simple, I tried disable the bluetooth for my app when the user close the app.
I need that if the user is with the app in background, the bluetooth maintain active, but if the user slide the app out of screen, the bluetooth closes.
I know how disable the bluetooth.
if (mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
}
Works perfectly, but I need call that 3 lines when the user close the app, I tried with onDestroy, onPause, onStop, but noone works for me.
onDestroy method is called when the user touch back button and the task go for background.
onPause method is called when the user touch the recents button, but the app is not closed.
onStop method same of onPause.
So... How to know when the user close the app?
Thank you
You can write a method to check if the app is running in background or not.
private boolean isAppIsInBackground(Context context) {
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;
}
This method returns true if the app is running in background.Then you can enable or disable bluetooth accordingly.
Also you can set a flag in your onResume and onPause methods of the BaseActivity which is extended by all other activitues so that you can check the flags to know whether app is running or not.
Make a BaseActivity and override its OnPause() method and extend
every Activity from BaseActivity .
I would also like to mention that onPause() is fired even when switching between multiple activities, so you'd need to track when it's pausing to go to another screen.
Reference : http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
If you want Bluetooth disabled when the user exits your activity, disable it in onBackPressed().

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 the top activity from android app in background service

In my app i want to check whethere any other app launches or not from my app.So i am currently usimg Activitymanager to find the top activity like this
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
But i want to run this code in background service.So that i can detect When other app launches through this.So is there any idea to do this.Plz help me.thanks
By using service you can achieve this..
public void checkActivity() {
handler = new Handler();
activityRunnable = new ActivityRunnable();
handler.postDelayed(activityRunnable, 500);
}
private class ActivityRunnable implements Runnable {
#Override
public void run() {
ActivityManager manager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
if (runningTasks != null && runningTasks.size() > 0) {
ComponentName topActivity = runningTasks.get(0).topActivity;
// Here you can get the TopActivity for every 500ms
if(!topActivity.getPackageName().equals(getPackageName())){
// Other Application is opened
}
handler.postDelayed(this, 500);
}
}
}
Call the checkActivity() in onCreate of service and dont forgot to remove the handler.removeCallbacks(activityRunnable); callbacks in onDestroy
start the service in LauncherActivity onCreate and stop the service in LauncherActivity onDestroy
Note: Dont forgot to add the permission in your manifest
<uses-permission android:name="android.permission.GET_TASKS" />
You should use Service for this. Then only you can achieve the background process..Please Go through about Services http://developer.android.com/guide/components/services.html and you can see this also http://www.vogella.com/articles/AndroidServices/article.html both URLs will help you
instead of service Use receiver to receive the launch event
and there you can implement this code.
The approach you are taking is wrong and prone to have your app rejected from the Google Play Store (plus it may stop working).
Check this thread to see possible ways to detect wether your app went to the background or not.

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
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.

Categories

Resources