创建活动与活动类的对象实例创建活动、实例、对象

2023-09-12 05:38:28 作者:囚。

我已经通过了一个Activity类:

I have got an Activity class by:

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

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

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

是否有可能通过创建这个活动的一个实​​例 activityClazz ?如果是这样,怎么样?

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

(我的code是一个独立的Java类,不在活动或服务。)

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

推荐答案

从技术上讲,你可以创建一个活动这样的一个实例。不过,这种情况将是无用的,因为它根本上下文就不会被建立起来。

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.

该规则是,你永远也不会打造的Andr​​oid组件的实例(活动服务的BroadcastReceiver 提供)自己(使用关键字或其他方式) 。这些类应该永远只由Android框架被创建,由于Android建立的基本上下文这些物体并可同时管理的生命周期。

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.