Android global variable

前端 未结 14 1085
眼角桃花
眼角桃花 2020-11-21 23:32

How can I create global variable keep remain values around the life cycle of the application regardless which activity running.

14条回答
  •  甜味超标
    2020-11-22 00:03

    There are a few different ways you can achieve what you are asking for.

    1.) Extend the application class and instantiate your controller and model objects there.

    public class FavoriteColorsApplication extends Application {
    
        private static FavoriteColorsApplication application;
        private FavoriteColorsService service;
    
        public FavoriteColorsApplication getInstance() {
            return application;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            application = this;
            application.initialize();
        }
    
        private void initialize() {
            service = new FavoriteColorsService();
        }
    
        public FavoriteColorsService getService() {
            return service;
        }
    
    }
    

    Then you can call the your singleton from your custom Application object at any time:

    public class FavoriteColorsActivity extends Activity {
    
    private FavoriteColorsService service = null;
    private ArrayAdapter adapter;
    private List favoriteColors = new ArrayList();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite_colors);
    
        service = ((FavoriteColorsApplication) getApplication()).getService();
        favoriteColors = service.findAllColors();
    
        ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
        adapter = new ArrayAdapter(this, R.layout.favorite_colors_list_item,
                favoriteColors);
        lv.setAdapter(adapter);
    }
    

    2.) You can have your controller just create a singleton instance of itself:

    public class Controller {
        private static final String TAG = "Controller";
        private static sController sController;
        private Dao mDao;
    
        private Controller() {
            mDao = new Dao();    
        }
    
        public static Controller create() {
            if (sController == null) {
                sController = new Controller();
            }
            return sController;
        }
    }
    

    Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

    3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

    I hope I gave enough detail in regards to how you can do what you are hoping for.

提交回复
热议问题