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. )
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
Technically, you can create an instance of an
Activity
like this. However, this instance would be useless because its underlyingContext
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 thenew
keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlyingContext
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.yes. you can get the activity context by using below line of code