简体   繁体   中英

How does your Application class know when the app has finished?

I've got a database singleton and I want to call .close() on it when the app finishes.

I can call .open() on the database in onCreate() in the Application class, but where do I call .close()?

Yeah what I do is sort of look for foreground activity. After each foreground activity dies, I can decrement. Once I reach zero and stay there for a reasonable amount of time, I know I am safe to close such resources. Ended up making virtual lifecycle callbacks in my app this way. So this way works no matter how many tasks you have or where things start from. IF you can only run and start your app from one place and everything goes only in a single linear fashion, then yes the root activity approach works too.

Specifically like this:

BaseActivity

public class BaseActivity extends Activity {

   public void onResume() {
      MyBaseApplicationType app = (MyBaseApplicationType)getApplicationContext();
      app.incrementForegroundActivity();
   }

   public void onPause() {
      MyBaseApplicationType app = (MyBaseApplicationType)getApplicationContext();
      app.decrementForegroundActivity();
   }

}

MyBaseApplication

public class MyBaseApplication extends Application {

   private int mForegroundActivities;
   private Handler mHandler;

   public void onCreate() {
      mHandler = new Handler();
   }

   public void decrementForegroundActivity() {
      mForegroundActivities--;
      if (mForegroundActivities == 0) {
         mHandler.postDelayed(mRunnable, 1000 /*about a second*/);
      }
   }

   public void incrementForegroundActivities() {
      mForegroundActivities++;
   }

   private Runnable mRunnable = new Runnable() {
      public void run() {
         if (mForegroundActivities == 0) {
            // Listeners of this broadcast can then clean up anything
            // as needed.
            Intent intent = new Intent("com.my.package.ACTION_BACKGROUNDED");
            sendBroadcast(intent);
         }
      }
   };

}

Generally you should close database connections in onDestroy() or onStop() . onDestroy() is called just before the activity is removed from memory and destroyed. onStop() is called when you go to a different application. Either one works, but onDestroy() is generally better because onStop() slows down app switching.

More info: http://developer.android.com/training/basics/activity-lifecycle/starting.html

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