Check whether activity is active

前端 未结 8 2260
眼角桃花
眼角桃花 2020-11-27 04:47

I\'m having a problem with a listener in a certain activity.

The problem is that this listener contains an alert.show(); which can be called after we try to push a

8条回答
  •  旧巷少年郎
    2020-11-27 05:18

    ArrayList runningactivities = new ArrayList();
    
    ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE); 
    
    List 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(); 
    
            alert.show()
        }
    

    This way you will know if the pointed activity is the current visible activity, else your alert will not display.

    This will only work when we navigate between two activities without finish.

提交回复
热议问题