简体   繁体   English

接收Activity的Android实用程序方法

[英]Android utility method that receives Activity

I have a separate Utility.class in my Android app and on this Utility.class I have setup a method that receives Activity and returns the stuff that I saved in SharedPreferences, like so: 我在Android应用程序中有一个单独的Utility.class,在此Utility.class上,我设置了一个方法,该方法接收Activity并返回保存在SharedPreferences中的内容,例如:

public static long retrieveFromSharedPrefs(Activity activity) {

    sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
    long startTime = sharedPref.getLong("StartTime", 0);

    return startTime;
}

The problem with this, is that when I try to access this method from a different class, I am not able to send this method the current activity: 这样做的问题是,当我尝试从其他类访问此方法时,无法将当前活动发送给该方法:

alreadyStartTime = Utilities.retrieveFromSharedPrefs(getActivity());

The problem is that getActivity() does not appear to be a valid API method, so I have no idea what to write there, the only API method he agrees to accept there is getParent() which has no effect at all (I'm not using fragments so it's not a child activity). 问题在于getActivity()似乎不是有效的API方法,所以我不知道在那里写什么,他同意接受的唯一API方法就是getParent(),它根本没有任何作用(我是不使用片段,因此这不是儿童活动)。

I will appreciate any help, thanks a lot!! 我将不胜感激,非常感谢! :) :)

You can access your shared preferences stuff from anywhere in an uniformed way: 您可以从任何地方以统一的方式访问共享的首选项:

PreferenceManager.getDefaultSharedPreferences(context)

just passing your current context 只是通过您当前的上下文

If you wish to access them from your own class you can use Application Context as an argument. 如果希望从自己的类访问它们,则可以使用“应用程序上下文”作为参数。

If you create your own application-derived class and register it in your Manifest you will be able to create getSharedPreference function you can use from everywhere 如果您创建自己的应用程序派生类并在清单中进行注册,则可以创建可以在任何地方使用的getSharedPreference函数

class MyApp extends Application {
private static MyApp instance;
public void onCreate() { this.instance = this; }
public static SharedPreferences prefs() { return PreferenceManager.getDefaultSharedPrefercnes(instance); }
}

But don't forget to include it into manifest in this case 但在这种情况下,请不要忘记将其包含在清单中

Actually you are not getting the activity in this function but the Activity's Context 实际上,您不是在此函数中获得活动,而是Activity's Context

The best practice for getting Context in a non-Activty class is using a ContextWrapper Class non-Activty类中获取Context的最佳实践是使用ContextWrapper

please check the following link ...you'll get a clear idea, how it's work 请检查以下链接...您将清楚知道它的工作原理

http://itekblog.com/android-context-in-non-activity-class/ http://itekblog.com/android-context-in-non-activity-class/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM