Search code examples
javaandroidservicefusedlocationproviderapiandroid-fusedlocation

How can I use Fused Location Provider inside a Service class?


I need to get the user's location in the background, so I am trying to use Fused Location Provider inside my Service class. I put the code below inside the onStart() method, but the context MainActivity.getAppContext() is not recognized. What can I use in its place, since I am using it in my Service class?

GoogleApi = new GoogleApiClient.Builder(MainActivity.getAppContext())
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();

Solution

  • A Service is a Context so from within the Service you can use this.

    Service also has getApplicationContext() that returns the application's context which is what it looks like MainActivity.getAppContext() was likely supposed to be returning. You could use that too.

    GoogleApi = new GoogleApiClient.Builder(getApplicationContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();