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

53,520

Solution 1

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;
}

Solution 2

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.

Solution 3

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().

Solution 4

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;
}

Solution 5

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

Share:
53,520

Related videos on Youtube

virsir
Author by

virsir

Updated on July 09, 2022

Comments

  • virsir
    virsir almost 2 years

    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
    virsir almost 14 years
    Any convenient method exist? like Activety::isActive()
  • Andy Zhang
    Andy Zhang almost 14 years
    I haven't personally come across or used such a method, but the above solution is very convenient too, in my opinion.
  • Moak
    Moak over 11 years
    This answer is a more rugged implementation stackoverflow.com/questions/3667022/…
  • Radu
    Radu over 11 years
    @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.
  • Crake
    Crake over 10 years
    You will need to call super.onResume(); to avoid a android.app.SuperNotCalledException
  • Nidhi
    Nidhi over 10 years
    Awesome solution.. Thanks.. :-)
  • yahya
    yahya about 10 years
    It returns true even if activity is onPause.. No use!
  • Vikalp
    Vikalp almost 9 years
    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.
  • Reaz Murshed
    Reaz Murshed almost 9 years
    Very nice solution. Thanks a lot!
  • Thirumalvalavan
    Thirumalvalavan over 8 years
    getRunningTasks method is deprecated. And it is removed in Android 6.
  • Subhasmith Thapa
    Subhasmith Thapa about 3 years
    Saved me time. Thanks @Melug