安卓获取当前的Activity即CurrentActivity

安卓获取当前的Activity即CurrentActivity有两种方法:

1.

在BaseActivity中 声明一个 :private static volatile Activity mCurrentActivity;

public static Activity getCurrentActivity() {
    return mCurrentActivity;
}

private void setCurrentActivity(Activity activity) {
    mCurrentActivity = activity;
}

在BaseActivity中的OnResume()方法中:

setCurrentActivity(this);

这样在外围直接获取就可以:

Activity currentActivity = BaseActivity.getCurrentActivity();

如果想判断比如:MainActivity是不是CurrentActivity 使用方法:

BaseActivity.getCurrentActivity() instanceof MainActivity 使用 instanceof 进行判断

第二种方法:

在CCApplication中定义一个:

private volatile Activity mCurrentActivity;并且添加get set方法
public synchronized Activity getCurrentActivity() {
    return mCurrentActivity;
}

public synchronized void setCurrentActivity(Activity activity) {
    mCurrentActivity = activity;
}

然后声明一个类:

private class CCActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

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

    @Override
    public void onActivityStarted(Activity activity) {
        MonkeyLog.d(TAG, "onActivityStarted :" + activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        mIsInForeground = true;
        Adjust.onResume();
        setCurrentActivity(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {
        mIsInForeground = false;
        Adjust.onPause();
        setCurrentActivity(null);
    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

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

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

在CCApplication的 onCreate()方法中调用:

registerActivityLifecycleCallbacks(new CCActivityLifecycleCallbacks());

在外围用的时候直接调用Get方法即可:

ActivityUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Activity currentActivity = CCApplication.getInstance().getCurrentActivity();
       if (currentActivity != null) {
           // TODO: 2018/8/15  
       }

    }
});

个人GitHub地址:https://github.com/HuaDanJson 欢迎关注

 

你可能感兴趣的:(安卓获取当前的Activity即CurrentActivity)