安卓实现随时获取Context(来自《第一行代码》)

来源:互联网 发布:64码高清网络电视官方 编辑:程序博客网 时间:2024/05/23 01:12

首先,定义类:MyApplication

package app.coolwhether.com.zhihu_16_5_31;import android.app.Application;import android.content.Context;/** * Created by Administrator on 2016/6/3. */public class MyApplication extends Application {    private static Context context;    @Override    public void onCreate() {        super.onCreate();        context = getApplicationContext();    }    public static Context getContext(){        return context;    }}

然后在AndroidManifest,

<application    android:name=".MyApplication"
告知系统,程序启动时,初始化MyApplication.

在引用时:即可获取Context。

MyApplication.getContext();

0 0
原创粉丝点击