create an instance of Activity with Activity class

2019-05-17 00:18发布

问题:

I have got an Activity class by:

Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());

String activityClassName = launchIntent.getComponent().getClassName();

Class<?> activityClazz = Class.forName(activityClassName);

Is it possible to create an instance of this Activity by using the activityClazz ? If so, how?

(My code is in a independent java class. Not in activity or service. )

回答1:

Technically, you can create an instance of an Activity like this. However, this instance would be useless because its underlying Context would not have been set up.

The rule is that you should never ever create instances of Android components (Activity, Service, BroadcastReceiver, Provider) yourself (using the new keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlying Context for these objects and also manages the lifecycle.

In short, your architecture is flawed if you need to create an instance of an Activity like this.



回答2:

Class.forName() needs the fully qualified name - that is, the name of the package the class is contained in, plus the simple name of the class itself.

Assuming the package containing the class is called com.your.package, the code would have to be

    String className = "com.your.package.Tab3";  // Change here
     Object obj= null;
    try {
        obj= Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


回答3:

yes. you can get the activity context by using below line of code

Activity activity = (Activity) getContext();