如何获取Activity的实例

 

1.假设你要获取的Activity的类名为MainActivity,在该类中声明一个该类的静态变量,并在onCreate()方法中实例化它,如下:

public class MainActivity{

       public static MainActivity instance = null;



       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
          setContentView(R.layout.main);

           instance = this;

       }

}

 

在另外一个类里面获取其实例:MainActivity.instance;

 

2.在不修改源代码的情况下利用反射机制获得

    @SuppressWarnings("unchecked")

    public  T getActivity(Class cls){ 

        Activity act = null;

        for (int i = 0, size = activityStack.size(); i < size; i++){

            act =  activityStack.get(i);

            if(act.getClass() == cls){ 

                return (T)act; 

            }

        }

        return null; 

    }

 

 

 

你可能感兴趣的:(Android开发)