android 如何在一个普通类的一个方法里面传递context参数?

比如我想把有关数据库sqlite的操作放在一个公共的当中,` MySqliteHelper mySqliteHelper=new MySqliteHelper(); //这个方法的第一个参数需要传递一个context的值,也就是activity.class的对象,请问对于一个普通的类,这个应该怎么传递??求指导

阅读 8.1k
1 个回答

创建方法

public Helper(Context context)
{
this.context = context;
}

-------------分割线--------------
在工具类里直接获取applicationContext,这样可以避免每次调用都传入context

先自己定义一个application

public class MyApplication extends Application {
    private static Context mContext;
    @Override
    public void onCreate(){
        super.onCreate();
        mContext = getApplicationContext();
    }
    public static Context getGlobalContext(){
        return mContext;
    }
}

然后在manifest中使用它

<application
        android:name="包名路径.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/app_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

工具类中这样使用就可以了

private NetworkHelper(){
        context = MyApplication.getGlobalContext();
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题