33

我正在开发一个具有多个活动的 Android 应用程序。在其中我有一个包含几个静态方法的类。我希望能够从不同的活动中调用这些方法。我正在使用静态方法通过 XmlResourceParser 从 xml 文件加载数据。要创建 XmlResourceParser,需要调用 Application Context。所以我的问题是,将应用程序上下文引用到静态方法中的最佳方法是什么?每个Activity都拿到并传入了吗?以某种方式将其存储在全局变量中?

4

4 回答 4

24

更好的方法是将 Activity 对象作为参数传递给静态函数。

AFAIK,没有这样的方法可以在静态方法中为您提供应用程序上下文。

于 2010-05-07T04:24:04.237 回答
4

这应该让您可以applicationContext从任何地方访问,让您可以在applicationContext任何可以使用它的地方访问;Toast, getString(), sharedPreferences, 等等。我已经多次使用它来进入applicationContext静态方法。

单身人士:

package com.domain.packagename;

import android.content.Context;

/**
 * Created by Versa on 10.09.15.
 */
public class ApplicationContextSingleton {
    private static PrefsContextSingleton mInstance;
    private Context context;

    public static ApplicationContextSingleton getInstance() {
        if (mInstance == null) mInstance = getSync();
        return mInstance;
    }

    private static synchronized ApplicationContextSingleton getSync() {
        if (mInstance == null) mInstance = new PrefsContextSingleton();
        return mInstance;
    }

    public void initialize(Context context) {
        this.context = context;
    }

    public Context getApplicationContext() {
        return context;
    }

}

在您的子类中初始化 Singleton Application

package com.domain.packagename;

import android.app.Application;

/**
 * Created by Versa on 25.08.15.
 */
public class mApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationContextSingleton.getInstance().initialize(this);
    }
}

如果我没记错的话,这给了你一个到处都是 applicationContext 的钩子,用它调用它ApplicationContextSingleton.getInstance.getApplicationContext(); 你不应该在任何时候清除它,因为当应用程序关闭时,它无论如何都会随之而来。

请记住更新AndroidManifest.xml以使用此Application子类:

<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.packagename"
    >

<application
    android:allowBackup="true"
    android:name=".mApplication" <!-- This is the important line -->
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:icon="@drawable/app_icon"
    >

如果您在这里发现任何问题,请告诉我,谢谢。:)

于 2015-09-25T12:25:46.160 回答
3

我不确定这是否会一直有效,但现在对我有用:

public class myActivity extends ListActivity
{
    public static Context baseContext;

    public void onCreate(Bundle savedInstanceState) 
    {
        baseContext = getBaseContext();
    }

然后你可以在你的包中使用静态:

myApplication.baseContext
于 2010-10-28T20:43:30.807 回答
1

Sane Tricks For InsaneWorld 博客中有一篇文章给出了答案。它说您可以用自己的子类替换 Application 对象,然后将应用程序上下文静态保留在那里。您可以在帖子中找到示例代码。

原始博客文章 - http://uquery.blogspot.co.il/2011/08/how-to-get-application-context.html

于 2013-04-13T16:49:57.070 回答