Android程序中任意位置获取Context

Context对象在Android中是一个很重要的内容,Activity中我们很容易获得该对象,然后在Service以及其他Class中并不是那么简单。下文介绍如何在任意位置获得Context对象。

1.创建一个类MyApplication,继承Application

public class MyApplication extends Application {
    private static MyApplication instance;
    public static MyApplication getInstance() {
        return instance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }   
}

 2.在AndroidManifest.xml文件中配置该类,android:name="com.hq.xxx.activity.MyApplication"这里写上完整的类名

 <application
        android:name="com.hq.xxx.activity.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
</application>

 3.在任意位置获得Context

Context context = MyApplication.getInstance().getApplicationContext();

猜你喜欢

转载自leoaioria.iteye.com/blog/2207596
今日推荐