Android 判断应用在前台还是后台

1、创建MApplication文件

import android.app.Application;

public class MApplication extends Application {
    private static MApplication mApplication;
    private AppLifecycleHandler lifecycleHandler;
    @Override
    public void onCreate() {
        super.onCreate();
        lifecycleHandler = new AppLifecycleHandler(); //register AppLifecycleHandler
        lifecycleHandler.onCreate();
    }

    public static MApplication getInstance() {
        if (mApplication == null) {
            mApplication = new MApplication();
        }
        return mApplication;
    }
}

2、创建AppLifecycleHandler文件

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * Monitor the application's foreground and background status
 */
public class AppLifecycleHandler implements Application.ActivityLifecycleCallbacks {
    private int runningActivities = 0;
    private static final String GET_APP_CONFIG_DEFAULT_TIMESTAMP = "0";
    private static final long ONE_SECOND = 1000L;
    private static long timeToBackground = 0L;

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        if (runningActivities == 0) {
            //应用在前台
        }
        runningActivities++;
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        runningActivities--;
        if (runningActivities == 0) {
          //应用在后台
        }
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }

    public void onCreate() {
        MApplication.getInstance().registerActivityLifecycleCallbacks(this);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值