Android开发者俱乐部

Context相关

2016-04-23  本文已影响60人  14cat

原文链接:
http://www.jianshu.com/p/979bc7eaa43b?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin#rd

前言

Context对象在我们的项目中实在是太常见了。启动Activity、Service、发送一个Broadcast,作为获取各种系统Resources的参数,Layout Inflation的参数,show a Dialog的参数等等,Context的使用不当,是可能造成内存泄漏的,当你的工程代码已经达到十几万行甚至几十万行时,Context对象就对内存泄漏造成非常可观的影响了,所以我们应该对Context对象的使用,做到心中有数

什么是Context

Context对象之间的差异

重写Context

public class LauncherApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        // 获取Application中的Context
        context = getApplicationContext();
    }

    /**
     * 获得Application的Context
     *
     * @return Context
     */
    public static Context getContext() {
        return context;
    }
}

清单文件配置

<application
    android:name=".LauncherApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

在界面中show a Dialog

public class MainActivity extends Activity {

    private Context application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        application = LauncherApplication.getContext();
    }

    public void ShowDialog (View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(application);
        builder.setTitle("ContextDemo");
        builder.setMessage("Context参数为applicationContext");
        builder.create();
        builder.show();
    }
}

lvik.system.NativeStart.main(thod)


Context相关的内存泄漏问题

错误的单例模式

public class Singleton {
    private static Single instance;
    private Context context;
    
    private Singleton(Context context) {
        this.mContext = context;
    }
    
    public static Singleton getInstance(Context context) {
        if (instance == null) {
            instance = new Singleton(mContext.getApplicationContext());
        }
        return instance;
    }
}

View持有Activity引用

public class MainActivity extends Activity {
    private static Drawable mDrawable;
    
    @Override
    protected void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_main);
        ImageView iv = new ImageView(this);
        mDrawable = getResources().getDrawable(R.drawable.ic_launcher);
        iv.setImageDrawable(mDrawable);
    }
}

正确使用Context

上一篇下一篇

猜你喜欢

热点阅读