How to get current foreground activity context in android?
Knowing that ActivityManager manages Activity, so we can gain information from ActivityManager. We get the current foreground running Activity by
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
UPDATE 2018/10/03
getRunningTasks() is DEPRECATED. see the solutions below.
This method was deprecated in API level 21.
As of Build.VERSION_CODES.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.
Android: How can I get the current foreground activity (from a service)?
Is there a native android way to get a reference to the currently running Activity from a service?
You may not own the "currently running Activity".
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
- Send a broadcast
Intent
to the activity -- here is a sample project demonstrating this pattern - Have the activity supply a
PendingIntent
(e.g., viacreatePendingResult()
) that the service invokes - Have the activity register a callback or listener object with the service via
bindService()
, and have the service call an event method on that callback/listener object - Send an ordered broadcast
Intent
to the activity, with a low-priorityBroadcastReceiver
as backup (to raise aNotification
if the activity is not on-screen) -- here is a blog post with more on this pattern
Android M: How can I get the current foreground activity package name(from a service)
you can use below code and get the current foreground activity package name.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(),
usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(
mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
currentApp = am.getRunningTasks(1).get(0).topActivity .getPackageName();
}
Edit
Add this permission in to Manifest file.
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
Note
Make sure you need to configure custom setting in your device to obtain the output you can config it with Setting > Security > Apps with usage access > Then enable your app permission
How to discover what Activity is on the foreground in Android app?
You have to implement onActivityPaused
and onActivityResumed()
public class YourApplication extends Application implements
Application.ActivityLifecycleCallbacks {
public static boolean isChatVisible=false;
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity p0, Bundle p1) {
}
@Override
public void onActivityStarted(Activity p0) {
}
@Override
public void onActivityResumed(Activity p0) {
isChatVisible=p0 instanceof ChatActivity;
}
@Override
public void onActivityPaused(Activity p0) {
}
@Override
public void onActivityStopped(Activity p0) {
}
}
Before building the notification just check YourApplication.isChatVisible()
How to get the package name of the current foreground activity?
The following method that returns Observable of current top package likely work:
public Observable<String> topPackageNameObservable() {
return Observable.fromCallable(() -> {
String topPackageName = "";
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> stats =
mUsageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_DAILY,
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1),
System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
} else {
topPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
} else {
topPackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
} catch (Exception e) {
e.printStackTrace();
}
return topPackageName;
});
}
How to find the current foreground activity in android
My guess is that it you need to look at the ActivityManager class. I took a brief look at the docs and this is what I came up with.
There's a function:
public List<ActivityManager.RunningTaskInfo> getRunningTasks (int maxNum)
From the Android docs:
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.
My thought would be if you pass in maxNum=1
, it should give you the most recent task that was run, ie. the top task. Each ActivityManager.RunningTaskInfo
has a property called topActivity
.
public ComponentName topActivity
From the Android docs: The activity component at the top of the history stack of the task. This is what the user is currently doing.
Getting the Foreground Activity of any application in a Service written in other application
What I want is that I need the reference to the current Activity of ANY application that is on the foreground.
That is not possible. Other applications are running in other processes; you do not have access to Java objects, such as Activity
instances, in those processes.
Way to get current running foreground app/process
first Add
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 200);
}
} else {
//Do work
}
Related Topics
How to Get the Source Code from an Apk File
How to Make My Custom Objects Parcelable
"Conversion to Dalvik Format Failed With Error 1" on External Jar
Developing For Android in Eclipse: R.Java Not Regenerating
How to Filter Specific Apps For Action_Send Intent (And Set a Different Text For Each App)
Difference Between Getcontext() , Getapplicationcontext() , Getbasecontext() and "This"
How Exactly Does the Android:Onclick Xml Attribute Differ from Setonclicklistener
How to Use External Jars in an Android Project
How to Get Ip Address of the Device from Code
Get Real Path from Uri, Android Kitkat New Storage Access Framework
How to Get Current Time and Date in Android
How to Implement Onbackpressed() in Fragments
How to Open a Url in Android'S Web Browser from My Application
How to Start New Activity on Button Click