Passing Activity to non-activity object properly(将活动正确传递给非活动对象)
问题描述
在我的应用程序中,我有一个非活动对象,它的角色是一个经理类.很多时候,我需要将源活动"作为参数传递给该管理器类的方法,以便对该活动进行一些操作.
In my app ive got a non-activity object which it's role is being a manager class. many times i need to pass "source activity" to methods as parameter to that manager class in order to make some operations on that activity.
例如,假设我们有 MyActivity 必须做一些祝酒词.所以我有一个名为 MyManager 的管理器类,我有这个方法
for example let's assume we have MyActivity which gotta do some toast. so i have this manager class called MyManager, and i have this method in it
raiseToast(Activity sourceActivity) {
Toast.makeText(sourceActivity, demo, Toast.LENGTH_LONG).show();
}
在 Myactivity 类中,我们以这种方式调用该方法:
and from Myactivity class we calling that method this way:
MyManager manager=new MyManager();
manager.raiseToast(MyActivity.this);
效果很好.
我在这里问的是,这是将 Activity 作为参数传递给非 Activity 对象的正确方法吗?我在真实设备(不是模拟器)上出现内存泄漏,我想知道这是否也会导致任何原因?
what I'm asking here, is this a proper way to pass an Activity as parameter to a non-activity object? I'm having a memory leaks on real device(not the emulator), I wonder if this could also causing any reason for that?
谢谢伊丹.
推荐答案
您可以尝试在活动中传递应用程序上下文,即 getApplicationContext().为什么你有这个 MyManager 对象?您可以从活动中举起吐司,而无需将其放在单独的班级中.将您的方法 raiseToast() 移动到活动主体并调用它.
You may try to pass application context which is getApplicationContext() on activity. Why do you have this MyManager object ? You can just raise toast from activity without having it in separate class. Move your method raiseToast() to activity body and just call it.
请阅读 http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html
这篇关于将活动正确传递给非活动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将活动正确传递给非活动对象


- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01