Using Application context everywhere?

后端 未结 9 887
难免孤独
难免孤独 2020-11-22 01:52

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instan         


        
相关标签:
9条回答
  • 2020-11-22 02:11

    There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.

    In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, if you pass the application Context into the LayoutInflater you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks.

    Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext() on a Context object (such as an Activity) to get the Application Context.

    0 讨论(0)
  • 2020-11-22 02:13

    I like it, but I would suggest a singleton instead:

    package com.mobidrone;
    
    import android.app.Application;
    import android.content.Context;
    
    public class ApplicationContext extends Application
    {
        private static ApplicationContext instance = null;
    
        private ApplicationContext()
        {
            instance = this;
        }
    
        public static Context getInstance()
        {
            if (null == instance)
            {
                instance = new ApplicationContext();
            }
    
            return instance;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:20

    You are trying to create a wrapper to get Application Context and there is a possibility that it might return "null" pointer.

    As per my understanding, I guess its better approach to call- any of the 2 Context.getApplicationContext() or Activity.getApplication().

    0 讨论(0)
提交回复
热议问题