Created
May 29, 2019 07:05
-
-
Save twlkyao/f5ef0ac444226f66c2bb7d7371e4c896 to your computer and use it in GitHub Desktop.
获取当前的activity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import java.lang.ref.WeakReference; | |
import java.util.Stack; | |
/** | |
* 获取当前的activity | |
* 两种思路: 1.弱引用持有当前activity | |
* 2.使用栈维护所有的activity,然后获取栈顶的activity | |
* 参考:https://www.jianshu.com/p/77f754446009 | |
*/ | |
public class ActivityStackManager { | |
private Stack<Activity> activities = new Stack<Activity>(); | |
private WeakReference<Activity> sCurrentActivityWeakRef; | |
public Activity getCurrentActivity() { | |
Activity currentActivity = null; | |
if (sCurrentActivityWeakRef != null) { | |
currentActivity = sCurrentActivityWeakRef.get(); | |
} | |
return currentActivity; | |
} | |
public void setCurrentActivity(Activity activity) { | |
sCurrentActivityWeakRef = new WeakReference<Activity>(activity); | |
} | |
public Activity getTopActivity(){ | |
if (activities != null && activities.size() > 0) { | |
return activities.peek(); | |
} | |
return null; | |
} | |
public void setTopActivity(Activity activity){ | |
if (activities != null && activities.size() > 0) { | |
if (activities.search(activity) == -1) { | |
activities.push(activity); | |
return; | |
} | |
int location = activities.search(activity); | |
if (location != 1) { | |
activities.remove(activity); | |
activities.push(activity); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment