23

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 ?

virsir
  • 15,159
  • 25
  • 75
  • 109
  • possible duplicate of [Checking if an Android application is running in the background](http://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background) – rds Jul 20 '15 at 15:41

7 Answers7

86

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;
}
Navid Rezaei
  • 1,003
  • 11
  • 22
Andy Zhang
  • 8,285
  • 1
  • 37
  • 24
  • 2
    Any convenient method exist? like Activety::isActive() – virsir Jul 16 '10 at 05:47
  • 7
    I haven't personally come across or used such a method, but the above solution is very convenient too, in my opinion. – Andy Zhang Jul 16 '10 at 06:34
  • This answer is a more rugged implementation http://stackoverflow.com/questions/3667022/android-is-application-running-in-background/5862048#5862048 – Moak Aug 28 '12 at 02:25
  • @Moak I would just say it is the solution to knowing if ANY of your app's activities are on screen. Therefor the solution linked by you is to a different, but related issue. – Radu Feb 11 '13 at 12:44
  • 4
    You will need to call super.onResume(); to avoid a android.app.SuperNotCalledException – Crake Sep 23 '13 at 20:07
  • 2
    This solution only works for android API 4.1+ . Below 4.1 you also need to override onWindowFocusChanged method of your activity to see if it really has focus or not. To test this scenario(Below API 4.1), you can press power button while your activity is running(onPause of your activity will be called) then press power button again(onResume of your activity will be called) but your app will not come to foreground until you open screen lock. – Vikalp Jul 01 '15 at 09:14
  • Very nice solution. Thanks a lot! – Reaz Murshed Jul 06 '15 at 10:33
7
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.

Samet
  • 917
  • 12
  • 26
5

I prefer not to handle the state by myself, so I have implemented a class that does this for me.

package mypackage;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

// Mine extends AppCompatActivity - your's might need to extend Activity, depending on whether
// you use the support library or not.
public class StateTrackingActivity extends AppCompatActivity {

    public enum ActivityState {

        CREATED, RESUMED, STARTED, PAUSED, STOPPED, DESTROYED
    }

    private ActivityState _activityState;

    protected ActivityState getActivityState() { return _activityState; }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        _activityState = ActivityState.CREATED;
    }

    @Override
    protected void onResume() {

        super.onResume();
        _activityState = ActivityState.RESUMED;
    }

    @Override
    protected void onStart() {

        super.onStart();
        _activityState = ActivityState.STARTED;
    }

    @Override
    protected void onPause() {

        super.onPause();
        _activityState = ActivityState.PAUSED;
    }

    @Override
    protected void onStop() {

        super.onStop();
        _activityState = ActivityState.STOPPED;
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        _activityState = ActivityState.DESTROYED;
    }
}

Then your activity can extend this one and you can get the state by calling getActivityState().

Minas Mina
  • 2,058
  • 3
  • 21
  • 35
3

This is my ultimate isActivityVisible function.

protected boolean isActivityVisible() {
    if (this.mActivity != null) {
        Class klass = this.mActivity.getClass();
        while (klass != null) {
            try {
                Field field = klass.getDeclaredField("mResumed");
                field.setAccessible(true);
                Object obj = field.get(this.mActivity);
                return (Boolean)obj;
            } catch (NoSuchFieldException exception1) {
//                Log.e(TAG, exception1.toString());
            } catch (IllegalAccessException exception2) {
//                Log.e(TAG, exception2.toString());
            }
            klass = klass.getSuperclass();
        }
    }
    return false;
}
Melug
  • 1,023
  • 9
  • 14
2
if (BaseActivity.this instanceof Faq)
            {
                Toast.makeText(BaseActivity.this, "You are in the Same Page", Toast.LENGTH_SHORT).show();
            }else {
                Intent intent = new Intent(BaseActivity.this, Faq.class);
                startActivity(intent);
                drawer.closeDrawer(GravityCompat.START);
            }

//// here am All my activities are extending on Activity called BaseActivity

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
Nishanth S Babu
  • 290
  • 3
  • 11
-1

There is Activity#isTaskRoot() method

Andrey
  • 77
  • 1
  • 11
-5
  if ( getActivity() instanceof ManageCardActivity){

   // your code
  }
JiTHiN
  • 6,548
  • 5
  • 43
  • 69
amit
  • 1