Passing Activity to non-activity object properly

孤街醉人 提交于 2019-12-30 02:19:10

问题


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.

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();
}

and from Myactivity class we calling that method this way:

MyManager manager=new MyManager();
manager.raiseToast(MyActivity.this);

it works fine.

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?

Thanks Idan.


回答1:


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.

EDIT: please read http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html



来源:https://stackoverflow.com/questions/2253088/passing-activity-to-non-activity-object-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!