代码之家  ›  专栏  ›  技术社区  ›  Slapout

在Android中将应用程序上下文转换为静态方法的最佳方法

  •  30
  • Slapout  · 技术社区  · 16 年前

    4 回复  |  直到 16 年前
        1
  •  23
  •   Karan    16 年前

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

        2
  •  3
  •   gjpc    15 年前

    public class myActivity extends ListActivity
    {
        public static Context baseContext;
    
        public void onCreate(Bundle savedInstanceState) 
        {
            baseContext = getBaseContext();
        }
    

    然后可以在包中使用static:

    myApplication.baseContext
    
        3
  •  3
  •   Versa    11 年前

    这应该可以让你进入 applicationContext 从任何允许你去的地方 任何可以使用它的地方; Toast , getString() , sharedPreferences 应用程序上下文 在静态方法内部多次。

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

    初始化 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 使用这个

    <?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"
        >
    

    如果您发现这里有什么问题,请告诉我,谢谢。:)

        4
  •  1
  •   Tom Susel    13 年前

    在《疯狂世界的理智把戏》的博客上有一篇文章给出了答案。 您可以在帖子中找到示例代码。

    http://uquery.blogspot.co.il/2011/08/how-to-get-application-context.html

    推荐文章