最近的在做一个SDK的项目,其中有一个需处求是用户在APP未被杀死的情况说下退出SDK超过一小时,再进入时会强制进入提示页面.最初的想法是退出SDK,也就是用户无操作,那我可以dispathtounchevent来拦截用户在页面的操作,在用户无操作时设置一个计时器开始计时,用户下次有操作是停止计时,当时真的觉得自己hin机智呢.后来直接被大哥pass了,大哥曰:"用户无操作,那用户如果在一个页面停留一小时啥操作也不做,也要提示吗?"emm..........大哥说的对,是小弟考虑不周,那么换个思路
从生命周期下手,朋友们都知道activity的七个生命周期,我就不多说了.
第一步放一个判断APP处于前台还是后台的工具类,具体忘了从哪位大神那里抄来的了,对不起了大神............
package com.csc108.phone.trade.util;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.format.DateUtils;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
/**
* 获取APP进入前台进入后台状态
*/
public class AppForegroundStateManager {
private static final String TAG = AppForegroundStateManager.class.getSimpleName();
private static final int MESSAGE_NOTIFY_LISTENERS = 1;
public static final long APP_CLOSED_VALIDATION_TIME_IN_MS = 30 * DateUtils.SECOND_IN_MILLIS; // 30 Seconds
private Reference mForegroundActivity;
private Set mListeners = new HashSet<>();
private AppForegroundState mAppForegroundState = AppForegroundState.NOT_IN_FOREGROUND;
private NotifyListenersHandler mHandler;
// 获得一个线程安全的类实例
private static class SingletonHolder {
public static final AppForegroundStateManager INSTANCE = new AppForegroundStateManager();
}
public static AppForegroundStateManager getInstance() {
return SingletonHolder.INSTANCE;
}
private AppForegroundStateManager() {
// 在主线程创建一个 handler
mHandler = new NotifyListenersHandler(Looper.getMainLooper());
}
public enum AppForegroundState {
IN_FOREGROUND,
NOT_IN_FOREGROUND
}
public interface OnAppForegroundStateChangeListener {
/** 当应用状态发生改变时这个方法被调用(隐藏到后台或显示到前台) */
void onAppForegroundStateChange(AppForegroundState newState);
}
/** 当 Activity 可见时应该调用这个方法 */
public void onActivityVisible(Activity activity) {
if (mForegroundActivity != null) mForegroundActivity.clear();
mForegroundActivity = new WeakReference<>(activity);
determineAppForegroundState();
}
/** 当 Activity 不再可见时应该调用这个方法 */
public void onActivityNotVisible(Activity activity) {
/*
* 前台 Activity 可能会被一个新的 Activity 替换。
* 如果新 Activity 与前台 Activity 匹配,仅仅清除前台 Activity
*/
if (mForegroundActivity != null) {
Activity ref = mForegroundActivity.get();
if (activity == ref) {
// This is the activity that is going away, clear the reference
mForegroundActivity.clear();
mForegroundActivity = null;
}
}
determineAppForegroundState();
}
/** 用于判断应用是否处于前台 */
public Boolean isAppInForeground() {
return mAppForegroundState == AppForegroundState.IN_FOREGROUND;
}
/**
* 用于判断当前状态,更新追踪的目标,并通知所有观察者状态是否发生了改变
*/
private void determineAppForegroundState() {
/* 获取当前状态 */
AppForegroundState oldState = mAppForegroundState;
/* 决定当前状态 */
final boolean isInForeground = mForegroundActivity != null && mForegroundActivity.get() != null;
mAppForegroundState = isInForeground ? AppForegroundState.IN_FOREGROUND : AppForegroundState.NOT_IN_FOREGROUND;
/* 如果新的状态与之前的状态不一样,则之前的状态需要通知所有观察者状态发生了改变 */
if (mAppForegroundState != oldState) {
validateThenNotifyListeners();
}
}
/**
* 添加一个用于监听前台应用状态的监听器
*
*/
public void addListener(@NonNull OnAppForegroundStateChangeListener listener) {
mListeners.add(listener);
}
/**
* 移除用于监听前台应用状态的监听器
*
*/
public void removeListener(OnAppForegroundStateChangeListener listener) {
mListeners.remove(listener);
}
/** 通知所有监听器前台应用状态发生了改变 */
private void notifyListeners(AppForegroundState newState) {
android.util.Log.i(TAG, "Notifying subscribers that app just entered state: " + newState);
for (OnAppForegroundStateChangeListener listener : mListeners) {
listener.onAppForegroundStateChange(newState);
}
}
/**
* 这个方法会通知所有观察者:前台应用的状态发生了改变
*
* 我们只在应用进入/离开前台时立刻监听器。当打开/关闭/方向切换这些操作频繁发生时,我们
* 简要的传递一个一定会被无视的 NOT_IN_FOREGROUND 值。为了实现它,当我们注意到状态发
* 生改变,一个延迟的消息会被发出。在这个消息被接收之前,我们不会注意前台应用的状态是否
* 发生了改变。如果在消息被延迟的那段时间内应用的状态发生了改变,那么该通知将会被取消。
*/
private void validateThenNotifyListeners() {
// If the app has any pending notifications then throw out the event as the state change has failed validation
if (mHandler.hasMessages(MESSAGE_NOTIFY_LISTENERS)) {
android.util.Log.v(TAG, "Validation Failed: Throwing out app foreground state change notification");
mHandler.removeMessages(MESSAGE_NOTIFY_LISTENERS);
} else {
if (mAppForegroundState == AppForegroundState.IN_FOREGROUND) {
// If the app entered the foreground then notify listeners right away; there is no validation time for this
mHandler.sendEmptyMessage(MESSAGE_NOTIFY_LISTENERS);
} else {
// We need to validate that the app entered the background. A delay is used to allow for time when the application went into the
// background but we do not want to consider the app being backgrounded such as for in app purchasing flow and full screen ads.
mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY_LISTENERS, APP_CLOSED_VALIDATION_TIME_IN_MS);
}
}
}
private class NotifyListenersHandler extends Handler {
private NotifyListenersHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message inputMessage) {
switch (inputMessage.what) {
// 解码完成
case MESSAGE_NOTIFY_LISTENERS:
/* 通知所有观察者状态发生了改变 */
android.util.Log.v(TAG, "App just changed foreground state to: " + mAppForegroundState);
notifyListeners(mAppForegroundState);
break;
default:
super.handleMessage(inputMessage);
}
}
}
}
第二步我们需要写一个baseactivity 在里边写上我们APP进入前台和后台的方法,以及如何判断APP进入后台一小时
@Override
protected void onStart() {
super.onStart();
//若last为0则首次进入,无需获取时间
if (last != 0) {
//获取当前时间
long cur = System.currentTimeMillis();
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
//判断当前时间和上次进入后台时的时间差大于一小时并且当前activity不是我们要强制显示的activity
if (cur - last > 3000 && !name.equals("PhoneLoginActivity")) {
Intent intent = new Intent(BaseActivity.this, PhoneLoginActivity.class);
intent.putExtra("phoneNum", phoneNum1);
startActivity(intent);
}
}
//前台可见状态
AppForegroundStateManager.getInstance().onActivityVisible(this);
}
@Override
protected void onPause() {
super.onPause();
if (this instanceof PhoneLoginActivity) {
last = 0;
}
}
@Override
protected void onStop() {
//进入后台时获取一次时间
//这里last是一个全局静态变量,刚开始的时候把时间存在本地,发现后边根本清不掉
last = System.currentTimeMillis();
//进入后台不可见
AppForegroundStateManager.getInstance().onActivityNotVisible(this);
super.onStop();
}
这里就已经是完成了,只需将需要显示提示的页面继承baseactivity即可.
说一个自己遇到的坑 时间刚开始只是在stop时获取一次,在start时再获取一次即可,后来发现这样提示页面会陷入死循环,点击返回之后三秒内(测试时将间隔时间设为了三秒)不点击的话会再开启一个当前页面,后来发现是生命周期在作祟,因为点击返回到上一个页面时,比如B---A,生命周期为 B onPause----A onCresate----A onStart----A onResume----B onStop, 可以发现在A可见之后B才会执行stop方法,所以last一直有值,所以在onPause中将last置空.
发言完毕,蟹蟹.