How to reference the current or main activity from another class

后端 未结 13 801
难免孤独
难免孤独 2021-01-30 12:39

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But ofte

相关标签:
13条回答
  • 2021-01-30 12:58

    Passing context is better way for refrence Activity.

    You can pass Context to another class.

    IN Activity ::

    AnotherClass Obj  = new AnotherClass(this);
    

    IN Another Class

    class AnotherClass{
    
    public AnotherClass(Context Context){
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-30 13:02

    Just a guess since I haven't done this but it might work.

    1) Get your applicationContext by making your Android Application class a Singleton.

    2) Get your ActivityManager class from the context.

    3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.

    4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.

    5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.

    Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.

    0 讨论(0)
  • 2021-01-30 13:04

    We built a framework for this. We have a BaseActivity class that inherits from Activity and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity that returns the activity on top of our privately-managed stack.

    It is kinda hacky, but it works. I'm not sure I would recommend it though.

    0 讨论(0)
  • 2021-01-30 13:04

    I solved this by making a singleton class has an instance of the class below as a member.

    public class InterActivityReferrer <T> {
        HashMap<Integer, T> map;
        ArrayList<Integer> reserve;
    
        public InterActivityReferrer() {
            map = new HashMap<>();
            reserve = new ArrayList<>();
        }
    
        public synchronized int attach(T obj) {
            int id;
            if (reserve.isEmpty()) {
                id = reserve.size();
            }
            else {
                id = reserve.remove(reserve.size() - 1);
            }
    
            map.put(id, obj);
            return id;
        }
    
        public synchronized T get(int id) {
            return map.get(id);
        }
    
        public synchronized T detach(int id) {
            T obj = map.remove(id);
            if (obj != null) reserve.add(id);
            return obj;
        }
    }
    

    This class can get a T object and return a unique integer assigned to the object by attach(). Assigned integers will not collide with each other unless HashMap fails. Each assigned integer will be freed when its corresponding object is detached by detach(). Freed integers will be reused when a new object is attached.

    And from a singleton class:

    public class SomeSingleton {
        ...
        private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
        ...
        public InterActivityReferrer<Activity> getReferrer() {return referrer;}
    }
    

    And from an activity that needs to be referred:

        ...
        int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
        ...
    

    Now with this, a unique integer corresponding to this activity instance is returned. And an integer can be delivered into another starting activity by using Intent and putExtra().

        ...
        Intent i = new Intent(this, AnotherActivity.class);
        i.putExtra("thisActivityID", activityID);
        startActivityForResult(i, SOME_INTEGER);
        ...
    

    And from the another activity:

        ...
        id refereeID = getIntent().getIntExtra("thisActivityID", -1);
        Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
        ...
    

    And finally the activity can be referred. And InterActivityReferrer can be used for any other class.

    I hope this helps.

    0 讨论(0)
  • 2021-01-30 13:05

    I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as a private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not generic Activity provided by adnroid.

    class blah extends Activity{
      private Activity activityReference;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            activityReference = this;
        }
    
    }
    after that you could use that the way you want, i.e. in

    Intent i = new Intent(activityReference, SomeOtherActivity.class)
    

    etc

    0 讨论(0)
  • 2021-01-30 13:06
    public static Activity getLaunchActivity()
    {
        final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
    
        final Method methodApp = activityThreadClass.getMethod("currentApplication");
        App = (Application) methodApp.invoke(null, (Object[]) null);
        Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
        launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
        Class<?> clazz;
        try
        {
            clazz = Class.forName(launchActivityInfo.name);
            if(clazz != null)
                return Activity.class.cast(clazz.newInstance());
        }
        catch (Exception e)
        {}
    
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题