Determining if an Activity exists on the current device - android

I want to know what activity is being displayed in android device
if the activity that I will search I execute code
if not I execute another code
purpose is to make an android service to check this task

This should work for you:
Get active Application name in Android
Just tweak it with the functionality you want, and you should be able to check rather easily.

Are you sure that's what you want?
purpose is to make an android service to check this task
If you told us what was the reason behind your "purpose", I'm almost sure we could help you with a better way of doing what you want (probably we could find a way which would waste less battery and which would antagonize less your users).
In any case, here is the answer to your question:
Use getRunningTasks of ActivityManager to get a list of the recently launched activities.
public
List
getRunningTasks (int maxNum)
Return a list of the tasks that are
currently running, with the most
recent being first and older ones
after in order. Note that "running"
does not mean any of the task's code
is currently loaded or activity -- the
task may have been frozen by the
system, so that it can be restarted in
its previous state when next brought
to the foreground.
You might also want to use the flag RECENT_WITH_EXCLUDED to make sure you get all the activities, even the ones that purposefully exclude themselves from that list.
public static final int RECENT_WITH_EXCLUDED
Added in API level 1 Flag for use with getRecentTasks(int, int):
return all tasks, even those that have set their
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS flag.

I found this code it works very well
Log.i("---------------", "----------onCreate--------------");
Log.i("-----test------", "----------1--------------");
ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
Log.i("-----test------", "----------2-------------");
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
Log.i("-----test------", "---------3--------------");
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.i("-----test------", "----------4--------------");
Log.i("------------------", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()+" Package Name : "+componentInfo.getPackageName());
Log.i("-----test------", "----------5--------------");

Related

Android: How to know what application is opened to foreground and do something when it goes to background

The title is bad, sorry. Could figure out how to say this in short.
So, I'm developing an application for Android which will only be used in my own couple tablets which are going to public use.
I need a service running in the background (or so I currently believe, prove me wrong if possible) which keeps track which application is foreground, and when that application goes to background the service starts activity which will go foreground and show something to the user(for example like some ad, or some review window which asks for start rating).
How could this be done?
Thank you.
E: The other applications can be 3rd party, so I can't modify the code of those.
When u start other activity at that time you current activity is OnPause() state and other activity goes onCreate() State.
You Must refer Activity LifeCycle for this.
You have to use Accessibility service. Starting from Android Lollipop you can't gather this kind of information. The only way is via accessibility docs.
to check other running tasks you should use ActivityManager.
ActivityManager acm = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> Ru_tasks = acm.getRunningTasks(NUMBER_OF_TASKS_U_WANT);
if (!Ru_tasks .isEmpty()) {
LOOP FOR EACH TASK (i is counter)
ComponentName topActivity = tasks.get(i).topActivity; // Or replace .topactivity with task name
if (topActivity.getPackageName().equals(WHAT_YOU LOOK FOR)) {
//Do WHAT YOU WANT!
}
}
get GET_TASKS permission

Close the service from the library only when the entire app goes to the background

I searched a lot in the net about it, the solutions are based on onPause and onDestroy. I want to give a library to a developer who just needs to paste a few lines of code from the library in his app which will enable the developer to create a service and destroy it when his entire app is in the background.
Does the Android OS send some kind of signals or intents when the app or the activity is changed (other than onPause or onStop method), so that i can catch that in a broadcast receiver from my library and do some actions.
If you know the package name of your app, try this (put this following snippet in the onCreate method of your app):
ActivityManager am= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
Then,
boolean exit = false;
while(!exit)
{
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if(!componentInfo.getPackageName().equals("Your package name"))
{
//Do your work here
exit = true;
}
}
When you start your app, this will be put into componentInfo. The taskInfo.get(0).topActivity will return the activity in the foreground. Hence you can know that your app has gone to the background by comparing package using the second code snippet.
Note:Put this second code snippet in an Asynctask so that the checking of whether the app has started can be done in the background.

How to notify when thirdparty application gets called

When third party apps in mobiles gets called i would like to notify user in a text message ..I am creating an app that will notify the user when i tries to open an application .
Help me to receive intent when ever app is tries to open..else sugges me some steps to find when the app icon is being clicked..
you can start a service, and execute every single minutes. Use ActivityManager to get the top activity in current running task. Something like this:
ActivityManager mActivityManager = (ActivityManager) context.getSystemService("activity");
ComponentName topActivity = mActivityManager.getRunningTasks(1).get(0).topActivity;
And then, you can do anything you want. Hope useful to u.
Don't forget the permission:
<uses-permission android:name="android.permission.GET_TASKS"/>

How to detect the state of an app other than mine?

I have looked around, but all suggestions are for checking state of my own app/activity.
using the Life Cycle.
I need to check if another app is in foreground/ running in background / paused .
Is it possible. Based on the state of the app i need to change my further actions.
ActivityManager acm=(ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = acm.getRunningTasks(1);
taskInfo.get(0).topActivity.getClassName();
ComponentName componentInfo = taskInfo.get(0).topActivity;
String packageName=componentInfo.getPackageName();
I used Activity manager to find the top package / activity if this matches the requrements i send a broadcast to the app that will update the info from the db. This can simply be done by registering a broadcast receiver using code in the onResume and Unregister it in OnPause.
So checking the Top package has just become a double check.

Determine if application on foreground - is that frowned upon?

There are lots of reasons why detecting if application is on foreground.
for example - as a trigger to GCM/C2DM push notification - lot's of apps would have good reason implementing different behavior when app is foreground and background.
Other reason could be - shotting down services consuming precious resources, such as querying servers in background task for instance.
Just to be clear: the definition (as I see it) for background app is:
application which none of it activities are invoked the onStart() method, and did not invoke yet the onStop() method.
that's because activity is visible to the user in it life cycle only at that time.
From the other hand -
seems like Google don't want application to react to the home button (it's not part of the API)
reacting to the onBackPressed() on the "root / main" activity as indicator for leaving Activity certainly not good idea (because lots of users using the home button, and not the back button)
there is no method in the API allowing determine if app is foreground (according to my definition..)
if I didn't miss something in the API, and it's really the case - Why there is no why to determine easily if the application is foreground or not????!!!!
what I know I can do to determine if the application is foreground is described in this thread - How to detect when an Android app goes to the background and come back to the foreground
but as #Emil saying - it's requiring special permission, or requiring some tricky logic's which very fast becoming problematic to maintain, and it smells like bad approach (although that's what I'm doing for now, because I don't have better idea...)
my questions basically are:
Is there no such API method from good reason?
Is taking into account if application is foreground or not is a bad approach?
Is there any other way to know if application is foreground or not?
is taking into account if application is foreground or not is a bad approach?
Taking foreground versus background into account is reasonable.
is there any other way to know if application is foreground or not?
You can roughly divide the scenarios for this into two groups:
Cases where you want to take an action immediately upon a change in the foreground/background status
Cases where some other event occurs (AlarmManager alarm, incoming system broadcast, etc.), and at that point you want to take different actions based upon whether or not you are in the foreground
In the former case, onUserLeaveHint() is your most reliable simple option. I cannot guarantee that it will cover all cases, but it should handle the HOME scenario, for example. You are also welcome to maintain a reference count of started activities in a static data member and try to use it instead.
In the latter case, an ordered broadcast can be useful.
With the new Android Architecture Components there is an easy way to know if your app is in the foreground or the background.
Just like with the activity scope lifecycle owner there is a general process lifecycle owner which you can subscribe to and get lifecycle updates.
For example:
Add this code in order to register as a lifecycle observer
ProcessLifecycleOwner.get().lifecycle.addObserver(lifecycleListener)
And this code in order to receive the relevant callbacks
#OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onApplicationOnStartEvent() {
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onApplicationOnStopEvent() {
}
Don't forget to remove the observer once you don't need it
ProcessLifecycleOwner.get().getLifecycle().removeObserver(lifecycleListener);
More information and examples can be found in this excellent article:
https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c
I had the same issue. I want to display push notification when my activity is not in foreground mode. Please go through following code and you will get your answer.
Context ctx = context.getApplicationContext();
ActivityManager am = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
PackageManager pm = this.getPackageManager();
try {
/**
* take fore ground activity name
*/
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (printLog == true) {
Log.d("Home", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
Log.d("Home", "Number Of Activities : "
+ taskInfo.get(0).numRunning);
Log.d("Home",
"Componenet Info : " + componentInfo.getPackageName());
Log.d("Home",
"Componenet Info : " + componentInfo.getClassName());
}
/**
* All activities name of a package to compare with fore ground
* activity. if match found, no notification displayed.
*/
PackageInfo info = pm.getPackageInfo(
"<PackageName>",
PackageManager.GET_ACTIVITIES);
ActivityInfo[] list = info.activities;
for (int i = 0; i < list.length; i++) {
Log.d("TAG","Activity : "+list[i].name);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
To use this, you have to take permission in your manifest file.
uses-permission android:name="android.permission.GET_TASKS"
Pardon me if I can't get your question.
If it is necessery for you to know if the app is on backround or foreground from a service that is running on the background(doesnt make sense otherwise), then you can just use binding, that is - bind to it on all your activities onResume, and unbind on all activities onPause. then in your service you can manage not only your application visibility to the user, but also which of the activities are open at any time. it is also leak-proof and more stable then a static variable (which can be cleaned up if necessery) as you are using android's API and relying on the correctness of the android OS code itself.

Categories

Resources