简体   繁体   中英

Android Activity life cycle issues

What I actually Wanted ?

In my app I have 4/5 activities and one background thread which talks with the server. I wanted to have some way to get the top most activity of my app. But surprisingly their was no way I could get that ?

What I did ?

After searching for a while, I implemented a variable mCurrentOnTopActivity of Type Activity and on onResume() and onPause() of every activity I set that variable. (That is actually a bad way).

Where I reached ?

Now their are cases in which after receiving some messages from the server I want to do some thing on UI thread ie show some dialogs or refresh ListView , now their is no way to check whether the mCurrentOnTopActivity refers an activiy which is actually running or not (finished or out Of focus for whatever reason).

What I want now ? Now I basically want help in following two problems:-

  1. How do I know which is the currently running top most activity of my App ?
  2. How do I know whether activity is still running or not (ie I want some thing like isActicitAlive() (imaginary function) which returns true between calls of onResume() and onPause() ?

I implemented 2 point using a variable in activity and setting it in onResume() and onPause() . But, is this the only way to do this ?

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

With this, you can check, whether the activity you are looking for is running or not.

esle, if you want to use the onStart() and onStop() methods, you can use the following code,

class MyActivity extends Activity {
     static boolean active = false;

      @Override
      public void onStart() {
         super.onStart();
         active = true;
      } 

      @Override
      public void onStop() {
         super.onStop();
         active = false;
      }
}

您可以使用服务绑定,以便只有最顶层的活动才能绑定到服务。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM