I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.
I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?
This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
When your Activity comes to the foreground, its onResume()
method will be invoked. When another Activity comes in front of your Activity, its onPause()
method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:
private boolean isInFront; @Override public void onResume() { super.onResume(); isInFront = true; } @Override public void onPause() { super.onPause(); isInFront = false; }
ArrayList<String> runningactivities = new ArrayList<String>(); ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE); List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE); for (int i1 = 0; i1 < services.size(); i1++) { runningactivities.add(0,services.get(i1).topActivity.toString()); } if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){ Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show(); }
This way you will know if the pointed activity is the current visible activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With