将活动正确传递给非活动对象

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

这篇关于将活动正确传递给非活动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)