Android中获取当前正在显示的Activity

头像 2019-09-0817:49:01 评论 267 ℃

1.监听Activity的生命周期

在Application的onCreate方法中监听Activity的生命周期

 registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
 
            }
 
            @Override
            public void onActivityStarted(Activity activity) {
 
            }
 
            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }
 
            @Override
            public void onActivityPaused(Activity activity) {
 
            }
 
            @Override
            public void onActivityStopped(Activity activity) {
 
            }
 
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
 
            }
 
            @Override
            public void onActivityDestroyed(Activity activity) {
 
            }
        });

2.保存当前Activity的状态

package cn.uniwa.uniwa.util;
 
import android.app.Activity;
 
import java.lang.ref.WeakReference;
 
/**
 * Created by zhoujian on 2018/1/19.
 */
 
public class MyActivityManager {
    
    private static MyActivityManager sInstance = new MyActivityManager();
    
    private WeakReference<Activity> sCurrentActivityWeakRef;
 
 
    private MyActivityManager() {
 
    }
 
    public static MyActivityManager getInstance() {
        return sInstance;
    }
 
    public Activity getCurrentActivity() {
        Activity currentActivity = null;
        if (sCurrentActivityWeakRef != null) {
            currentActivity = sCurrentActivityWeakRef.get();
        }
        return currentActivity;
    }
 
    public void setCurrentActivity(Activity activity) {
        sCurrentActivityWeakRef = new WeakReference<Activity>(activity);
    }
 
}

如果是网络请求 记得使用 runONRuiThread()

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
头像
百度云盘1T空号
百度云盘2T空号

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: