Android 如何从另一个类引用当前或主要活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11227591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reference the current or main activity from another class
提问by AndroidDev
I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager
, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?
我经常发现自己需要访问需要引用某些活动的方法。例如,要使用getWindowManager
,我需要访问一些活动。但通常我使用这些方法的代码在其他一些没有引用活动的类中。到目前为止,我要么存储了对主要活动的引用,要么将某些活动的上下文传递给了类。有没有更好的方法来做到这一点?
回答by Alessandro Muzzi
If you already have a valid context, just use this:
Activity activity = (Activity) context;
如果您已经有一个有效的上下文,只需使用这个:
Activity activity = (Activity) context;
回答by Samir Mangroliya
Passing context is better way for refrence Activity.
传递上下文是参考活动的更好方式。
You can pass Context to another class.
您可以将 Context 传递给另一个类。
IN Activity ::
活动中::
AnotherClass Obj = new AnotherClass(this);
IN Another Class
在另一个班级
class AnotherClass{
public AnotherClass(Context Context){
}
}
回答by Vladimir Ivanov
回答by Darrell Higgins
I found a way to get the Activity to a non-activity class that I have not seen discussed in forums. This was after numerous failed attempts at using getApplicationContext() and of passing the context in as a parameter to constructors, none of which gave Activity. I saw that my adapters were casting the incoming context to Activity so I made the same cast to my non-activity class constructors:
我找到了一种方法,可以将 Activity 转到我在论坛中未讨论过的非活动类。这是在多次尝试使用 getApplicationContext() 并将上下文作为参数传递给构造函数的尝试失败之后,没有一个给 Activity。我看到我的适配器正在将传入的上下文转换为 Activity,因此我对非活动类构造函数进行了相同的转换:
public class HandleDropdown extends Application{
...
public Activity activity;
...
public HandleDropdown() {
super();
}
public HandleDropdown(Activity context) {
this.activity = context;
this.context = context;
}
public void DropList(View v,Activity context) {
this.activity = context;
this.context = context;
...
}
After doing this cast conversion of Context to Activity I could use this.activity wherever I needed an Activity context.
在将 Context 转换为 Activity 之后,我可以在需要 Activity 上下文的任何地方使用 this.activity。
回答by Stefano Ortisi
There are many ways for Activities communication.
活动通信有多种方式。
you can use:
您可以使用:
the startActivityForResult method
a system of broadcast message and receiver (you can broadcast an event from the actual activity, and register a receiver in the target activity. Remember that the target activity must be previously initialized and non finished)
- as you say, store a reference of the target activity wherever you need.
startActivityForResult 方法
一个广播消息和接收器的系统(您可以从实际活动中广播一个事件,并在目标活动中注册一个接收者。记住,目标活动必须事先初始化且未完成)
- 正如您所说,在您需要的任何地方存储目标活动的引用。
回答by drcat
I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as a private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not generic Activity provided by adnroid.
我是 android 新手,所以我的建议可能看起来很笨拙,但是如果您只是将您的活动的引用创建为私有属性并在 OnCreate 方法中分配它呢?您甚至可以像这样使用 OnCreate 创建您的 CustomActivity 并从您的 CustomActivity 派生您的所有活动,而不是由 adnroid 提供的通用活动。
class blah extends Activity{
private Activity activityReference;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityReference = this;
}
}
Intent i = new Intent(activityReference, SomeOtherActivity.class)
etc
等等
回答by Bojan Radivojevic Bomber
You can make you application instance a singleton, and use it when you need a Context
您可以使您的应用程序实例成为单例,并在需要 Context 时使用它
An example is in this question:
Android Application as Singleton
这个问题中的一个例子:
Android Application as Singleton
This way, when you need a Context, you can get it withContext context = MyApplication.getInstance()
这样,当你需要一个上下文时,你可以用Context context = MyApplication.getInstance()
This might not be the cleanest solution, but it has worked well for me so far
这可能不是最干净的解决方案,但到目前为止它对我来说效果很好
回答by David Wasser
We built a framework for this. We have a BaseActivity
class that inherits from Activity
and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity
that returns the activity on top of our privately-managed stack.
我们为此构建了一个框架。我们有一个BaseActivity
继承自Activity
并覆盖所有生命周期方法的类,并有一些静态(类)变量来跟踪活动堆栈。如果有什么想知道当前活动是什么,它只是调用一个静态方法,BaseActivity
该方法返回我们私有管理堆栈顶部的活动。
It is kinda hacky, but it works. I'm not sure I would recommend it though.
这有点hacky,但它有效。我不确定我会推荐它。
回答by Chrome K
I solved this by making a singleton class has an instance of the class below as a member.
我通过使单例类具有以下类的实例作为成员来解决此问题。
public class InterActivityReferrer <T> {
HashMap<Integer, T> map;
ArrayList<Integer> reserve;
public InterActivityReferrer() {
map = new HashMap<>();
reserve = new ArrayList<>();
}
public synchronized int attach(T obj) {
int id;
if (reserve.isEmpty()) {
id = reserve.size();
}
else {
id = reserve.remove(reserve.size() - 1);
}
map.put(id, obj);
return id;
}
public synchronized T get(int id) {
return map.get(id);
}
public synchronized T detach(int id) {
T obj = map.remove(id);
if (obj != null) reserve.add(id);
return obj;
}
}
This class can get a T object and return a unique integer assigned to the object by attach(). Assigned integers will not collide with each other unless HashMap fails. Each assigned integer will be freed when its corresponding object is detached by detach(). Freed integers will be reused when a new object is attached.
这个类可以获取一个 T 对象并返回一个由 attach() 分配给该对象的唯一整数。除非 HashMap 失败,否则分配的整数不会相互冲突。当其对应的对象被 detach() 分离时,每个分配的整数将被释放。当附加新对象时,释放的整数将被重用。
And from a singleton class:
从单例类:
public class SomeSingleton {
...
private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
...
public InterActivityReferrer<Activity> getReferrer() {return referrer;}
}
And from an activity that needs to be referred:
并且来自需要引用的活动:
...
int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
...
Now with this, a unique integer corresponding to this activity instance is returned. And an integer can be delivered into another starting activity by using Intent and putExtra().
现在,与此活动实例对应的唯一整数将被返回。并且可以使用 Intent 和 putExtra() 将整数传递到另一个起始活动中。
...
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("thisActivityID", activityID);
startActivityForResult(i, SOME_INTEGER);
...
And from the another activity:
从另一个活动:
...
id refereeID = getIntent().getIntExtra("thisActivityID", -1);
Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
...
And finally the activity can be referred. And InterActivityReferrer can be used for any other class.
最后可以参考活动。并且 InterActivityReferrer 可用于任何其他类。
I hope this helps.
我希望这有帮助。
回答by Ali Bagheri
public static Activity getLaunchActivity()
{
final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
final Method methodApp = activityThreadClass.getMethod("currentApplication");
App = (Application) methodApp.invoke(null, (Object[]) null);
Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
Class<?> clazz;
try
{
clazz = Class.forName(launchActivityInfo.name);
if(clazz != null)
return Activity.class.cast(clazz.newInstance());
}
catch (Exception e)
{}
return null;
}