Android 如何检查我的活动是否是在屏幕中运行的当前活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3262157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:20:56  来源:igfitidea点击:

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

androidandroid-activityscreenlifecycle

提问by virsir

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.

我使用 Toast 来发出通知,但即使它的活动不在当前屏幕中并且其他一些活动已经启动,它似乎也会出现。

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 ?

我想检查这种情况,当活动不是当前活动时,我不会发送 Toast 通知。但是怎么办?

回答by Andy Zhang

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:

当您的 Activity 进入前台时,onResume()将调用其方法。当另一个 Activity 出现在您的 Activity 前面时,onPause()将调用其方法。所以你需要做的就是实现一个布尔值,指示你的 Activity 是否在前台:

private boolean isInFront;

@Override
public void onResume() {
    super.onResume();
    isInFront = true;
}

@Override
public void onPause() {
    super.onPause();
    isInFront = false;
}

回答by Samet

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.

通过这种方式,您将知道指向的活动是否是当前可见的活动。

回答by Minas Mina

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

然后你的 Activity 可以扩展这个,你可以通过调用getActivityState().

回答by Melug

This is my ultimate isActivityVisible function.

这是我的终极 isActivityVisible 函数。

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

回答by Nishanth S Babu

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

//// 这里是我所有的活动都在名为 BaseActivity 的活动上进行扩展

回答by Andrey

回答by amit

  if ( getActivity() instanceof ManageCardActivity){

   // your code
  }