android監聽前後臺切換
阿新 • • 發佈:2019-02-09
公司的需求是這樣的,APP切換到前臺是向伺服器傳送資料,切換到後臺是也傳送資料。網上這方面的方法很多也很雜,還不好用,這裡介紹一種完美的解決方法,無論是back鍵還是home鍵切換到後臺都可以監聽,甚至通過後臺殺死APP程序都逃不過。
首先寫一個工具類:
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
/**
* Created by Administrator on 2018/3/20.
*/
public class AppFrontBackHelper {
private OnAppStatusListener mOnAppStatusListener;
public AppFrontBackHelper() {
}
/**
* 註冊狀態監聽,僅在Application中使用
*
* @param application
* @param listener
*/
public void register(Application application, OnAppStatusListener listener) {
mOnAppStatusListener = listener;
application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
public void unRegister(Application application) {
application.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
private Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
//開啟的Activity數量統計
private int activityStartCount = 0;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
activityStartCount++;
//數值從0變到1說明是從後臺切到前臺
if (activityStartCount == 1) {
//從後臺切到前臺
if (mOnAppStatusListener != null) {
mOnAppStatusListener.onFront();
}
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
activityStartCount--;
//數值從1到0說明是從前臺切到後臺
if (activityStartCount == 0) {
//從前臺切到後臺
if (mOnAppStatusListener != null) {
mOnAppStatusListener.onBack();
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
};
public interface OnAppStatusListener {
void onFront();
void onBack();
}
}
然後自定義一個類,繼承Application,這個類的名字先別亂起,看看清單檔案 application下是否有name標籤,如果有就用這個名字命名這個類,如果沒有就新增一個name標籤,name的值要和這個類的名稱一致。
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
AppFrontBackHelper helper = new AppFrontBackHelper();
helper.register(MyApp.this, new AppFrontBackHelper.OnAppStatusListener() {
@Override
public void onFront() {
//應用切到前臺處理
Log.i("info","前臺");
}
@Override
public void onBack() {
//應用切到後臺處理
Log.i("info","後臺");
}
});
}
}
這樣就OK了。