创建活动与活动类的对象实例 [英] create an instance of Activity with Activity class object

查看:98
本文介绍了创建活动与活动类的对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过了一个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.

这篇关于创建活动与活动类的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆