Android app前后台切换监听

Android app前后台切换监听_第1张图片

目前正在开发的app使用WebSocket传输实时数据,为了更好的用户体验,需要app退至后台时主动断开长连接,当用户再次切换进入前台程序时链接长连接;

实现起来非常简单,自定义Application,在onCreate中添加监听即可

   private fun initAppStatusListener() {

        ForegroundCallbacks.init(this).addListener(object : ForegroundCallbacks.Listener {
            override fun onBecameForeground() {
                Toast.makeText(context, "++++App进入前台++++", Toast.LENGTH_SHORT).show()
            }

            override fun onBecameBackground() {
                Toast.makeText(context, "----App退至后台----", Toast.LENGTH_SHORT).show()
            }
        })

    }

 onCreate有时候会执行多次,比如集成部分三方库以后,app启动时自身和三方库都会调用

    override fun onCreate() {
        super.onCreate()
        
        val curProcess = getProcessName(this, android.os.Process.myPid())
        if (packageName != curProcess) return
        
        mApplication = this
        initAppStatusListener()
    }

    // 进程名
    private String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

下面直接贴上ForegroundCallbacks代码

/**
 * Created by roy on 2018/11/15 0015.
 * 前台后台切换监听
 */
public class ForegroundCallbacks implements Application.ActivityLifecycleCallbacks {

    private static final long CHECK_DELAY = 600;
    private static ForegroundCallbacks instance;
    private boolean foreground = false, paused = true;
    private Handler handler = new Handler();
    private List listeners = new CopyOnWriteArrayList<>();
    private Runnable check;

    public static ForegroundCallbacks init(Application application) {
        if (instance == null) {
            instance = new ForegroundCallbacks();
            application.registerActivityLifecycleCallbacks(instance);
        }
        return instance;
    }

    public static ForegroundCallbacks get(Application application) {
        if (instance == null) {
            init(application);
        }
        return instance;
    }

    public static ForegroundCallbacks get(Context ctx) {
        if (instance == null) {
            Context appCtx = ctx.getApplicationContext();
            if (appCtx instanceof Application) {
                init((Application) appCtx);
            }
            throw new IllegalStateException("Foreground is not initialised and " + "cannot obtain the Application object");
        }
        return instance;
    }

    public static ForegroundCallbacks get() {
        return instance;
    }

    public boolean isForeground() {
        return foreground;
    }

    public boolean isBackground() {
        return !foreground;
    }

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    public void removeListener(Listener listener) {
        listeners.remove(listener);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        paused = false;
        boolean wasBackground = !foreground;
        foreground = true;
        if (check != null)
            handler.removeCallbacks(check);
        if (wasBackground) {
            for (Listener l : listeners) {
                try {
                    l.onBecameForeground();
                } catch (Exception exc) {
                    Log.i("ForegroundCallbacks",exc.getMessage());
                }
            }
        } 
    }

    @Override
    public void onActivityPaused(Activity activity) {
        paused = true;
        if (check != null) handler.removeCallbacks(check);
        handler.postDelayed(check = new Runnable() {
            @Override
            public void run() {
                if (foreground && paused) {
                    foreground = false;
                    for (Listener l : listeners) {
                        try {
                            l.onBecameBackground();
                        } catch (Exception exc) {
                            Log.i("ForegroundCallbacks",exc.getMessage());
                        }
                    }
                } 
            }
        }, CHECK_DELAY);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
    }

    public interface Listener {
        public void onBecameForeground();

        public void onBecameBackground();
    }
    
}

 

你可能感兴趣的:(android)