前言
Context对象在我们的项目中实在是太常见了。启动Activity、Service、发送一个Broadcast,作为获取各种系统Resources的参数,Layout Inflation的参数,show a Dialog的参数等等,Context的使用不当,是可能造成内存泄漏的,当你的工程代码已经达到十几万行甚至几十万行时,Context对象就对内存泄漏造成非常可观的影响了,所以我们应该对Context对象的使用,做到心中有数
什么是Context
- Context是为一个Android程序提供各种功能、资源、服务的一个环境,Context的资源系统中只有一套,因为它的子类(Application,Activity,Service)对这同一块资源处理方式的不同,让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">
- 配置完 android:name这个属性,以后应用使用的就是你自定义的Application
在界面中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();
}
}
-
点击后闪退闪退信息
04-21 04:43:21.590 2104-2104/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.cat14.demo, PID: 2104 java.lang.IllegalStateException: Could not execute method of the activity at android.view.View$1.onClick(View.java:3823) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at android.view.View$1.onClick(View.java:3818) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application at android.view.ViewRootImpl.setView(ViewRootImpl.java:540) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:286) at android.app.AlertDialog$Builder.show(AlertDialog.java:951) at com.cat14.demo.MainActivity.ShowDialog(MainActivity.java:26) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at android.view.View$1.onClick(View.java:3818) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
lvik.system.NativeStart.main(thod)
- 可见,当使用Application的Context时,是无法弹出一个Dialog的,因为Dialog作为一个View,依附在Activity上,并且与Theme相关,当传入参数为Activity的Context时,崩溃就解决了
-
Context对象之间的使用上的差异
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;
}
}
- 这是一个非线程安全的单例模式
- Activity A去getInstance获得instance对象,传入this
- 常驻内存的Singleton保存了你传入的Activity A对象,并一直持有
- 即时Activity被销毁掉,但因为它的引用还存在于一个Singleton中,就不可能被GC掉,这样就导致了内存泄漏
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);
}
}
- 有一个静态的Drawable对象
- 当ImageView设置这个Drawable时,ImageView保存了mDrawable的引用
- 而ImageView传入的this,是MainActivity的mContext
- 因为被static修饰的mDrawable是常驻内存的,MainActivity是它的间接引用
- MainActivity被销毁时,也不能被GC掉,所以造成内存泄漏
正确使用Context
- 一般Context造成的内存泄漏,几乎都是当Context销毁的时候,却因为被引用导致销毁失败
- 而Application的Context对象可以理解为随着进程存在的,所以当Application的Context能搞定的情况下,并且生命周期长的对象,优先使用Application的Context
- 内存检测的自动化工具,LeakCanary