create an instance of Activity with Activity class

2019-05-16 23:43发布

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. )

3条回答
该账号已被封号
2楼-- · 2019-05-17 00:15

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楼-- · 2019-05-17 00:41

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.

查看更多
我只想做你的唯一
4楼-- · 2019-05-17 00:41

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

Activity activity = (Activity) getContext();
查看更多
登录 后发表回答