码迷,mamicode.com
首页 > 移动开发 > 详细

Android 前台与后台监听

时间:2015-08-31 23:12:27      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:

  1 package com.triaged.badge.helpers;
  2 
  3 import android.app.Activity;
  4 import android.app.Application;
  5 import android.content.Context;
  6 import android.os.Bundle;
  7 import android.os.Handler;
  8 
  9 import com.triaged.badge.app.App;
 10 
 11 import java.util.List;
 12 import java.util.concurrent.CopyOnWriteArrayList;
 13 
 14 /**
 15  * Usage:
 16  *
 17  * 1. Get the Foreground Singleton, passing a Context or Application object unless you
 18  * are sure that the Singleton has definitely already been initialised elsewhere.
 19  *
 20  * 2.a) Perform a direct, synchronous check: Foreground.isForeground() / .isBackground()
 21  *
 22  * or
 23  *
 24  * 2.b) Register to be notified (useful in Service or other non-UI components):
 25  *
 26  *   Foreground.Listener myListener = new Foreground.Listener(){
 27  *       public void onBecameForeground(){
 28  *           // ... whatever you want to do
 29  *       }
 30  *       public void onBecameBackground(){
 31  *           // ... whatever you want to do
 32  *       }
 33  *   }
 34  *
 35  *   public void onCreate(){
 36  *      super.onCreate();
 37  *      Foreground.get(this).addListener(listener);
 38  *   }
 39  *
 40  *   public void onDestroy(){
 41  *      super.onCreate();
 42  *      Foreground.get(this).removeListener(listener);
 43  *   }
 44  */
 45 public class Foreground implements Application.ActivityLifecycleCallbacks {
 46 
 47     public static final long CHECK_DELAY = 500;
 48     public static final String TAG = Foreground.class.getName();
 49 
 50     public interface Listener {
 51 
 52         public void onBecameForeground();
 53 
 54         public void onBecameBackground();
 55 
 56     }
 57 
 58     private static Foreground instance;
 59 
 60     private boolean foreground = false, paused = true;
 61     private Handler handler = new Handler();
 62     private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
 63     private Runnable check;
 64 
 65     /**
 66      * Its not strictly necessary to use this method - _usually_ invoking
 67      * get with a Context gives us a path to retrieve the Application and
 68      * initialise, but sometimes (e.g. in test harness) the ApplicationContext
 69      * is != the Application, and the docs make no guarantees.
 70      *
 71      * @param application
 72      * @return an initialised Foreground instance
 73      */
 74     public static Foreground init(Application application){
 75         if (instance == null) {
 76             instance = new Foreground();
 77             application.registerActivityLifecycleCallbacks(instance);
 78         }
 79         return instance;
 80     }
 81 
 82     public static Foreground get(Application application){
 83         if (instance == null) {
 84             init(application);
 85         }
 86         return instance;
 87     }
 88 
 89     public static Foreground get(Context ctx){
 90         if (instance == null) {
 91             Context appCtx = ctx.getApplicationContext();
 92             if (appCtx instanceof Application) {
 93                 init((Application)appCtx);
 94             }
 95             throw new IllegalStateException(
 96                     "Foreground is not initialised and " +
 97                             "cannot obtain the Application object");
 98         }
 99         return instance;
100     }
101 
102     public static Foreground get(){
103         if (instance == null) {
104             throw new IllegalStateException(
105                     "Foreground is not initialised - invoke " +
106                             "at least once with parameterised init/get");
107         }
108         return instance;
109     }
110 
111     public boolean isForeground(){
112         return foreground;
113     }
114 
115     public boolean isBackground(){
116         return !foreground;
117     }
118 
119     public void addListener(Listener listener){
120         listeners.add(listener);
121     }
122 
123     public void removeListener(Listener listener){
124         listeners.remove(listener);
125     }
126 
127     @Override
128     public void onActivityResumed(Activity activity) {
129         paused = false;
130         boolean wasBackground = !foreground;
131         foreground = true;
132 
133         if (check != null)
134             handler.removeCallbacks(check);
135 
136         if (wasBackground){
137             App.gLogger.i( "went foreground");
138             for (Listener l : listeners) {
139                 try {
140                     l.onBecameForeground();
141                 } catch (Exception exc) {
142                    App.gLogger.e( "Listener threw exception!", exc);
143                 }
144             }
145         } else {
146             App.gLogger.i( "still foreground");
147         }
148     }
149 
150     @Override
151     public void onActivityPaused(Activity activity) {
152         paused = true;
153 
154         if (check != null)
155             handler.removeCallbacks(check);
156 
157         handler.postDelayed(check = new Runnable(){
158             @Override
159             public void run() {
160                 if (foreground && paused) {
161                     foreground = false;
162                     App.gLogger.i( "went background");
163                     for (Listener l : listeners) {
164                         try {
165                             l.onBecameBackground();
166                         } catch (Exception exc) {
167                            App.gLogger.e( "Listener threw exception!", exc);
168                         }
169                     }
170                 } else {
171                     App.gLogger.i( "still foreground");
172                 }
173             }
174         }, CHECK_DELAY);
175     }
176 
177     @Override
178     public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
179 
180     @Override
181     public void onActivityStarted(Activity activity) {}
182 
183     @Override
184     public void onActivityStopped(Activity activity) {}
185 
186     @Override
187     public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
188 
189     @Override
190     public void onActivityDestroyed(Activity activity) {}
191 }

 

Android 前台与后台监听

标签:

原文地址:http://www.cnblogs.com/robinxdroid/p/4774363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!