Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if my activity is the current activity running in the screen

Tags:

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 ?

like image 979
virsir Avatar asked Jul 16 '10 05:07

virsir


People also ask

How can I get current activity?

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.


2 Answers

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; } 
like image 138
Andy Zhang Avatar answered Oct 04 '22 22:10

Andy Zhang


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.

like image 44
Samet Avatar answered Oct 04 '22 23:10

Samet