Search code examples
androidfusedlocationproviderapi

Fused location provider singleton example?


Hi is it possible to create a fused location provider singleton which can be used to get the last location from many activities?

In addition how would i maintain an Google Api Client instance across these activities in terms of connect and disconnect.


Solution

  • It is possible. You will want to implement the private constructor/ getInstance() combo --

    /**
     * Private constructor.
     */   
    private GPSPlotter(Context theContext) {
        initializeInstance();
        initializeFields(theContext);
        buildApiClient();
        connectClient();
    }
    
    /**
     * Returns an instance of the GPS Plotter.
     */
    public static GPSPlotter getInstance(Context theContext) {
    
        if (gpsPlotterInstance == null)
            return new GPSPlotter(theContext);
        else
            return gpsPlotterInstance;
    
    }
    

    I'm fairly certain passing Context as a parameter to model objects breaks with Android convention, but structuring your code like this should work.