Java tutorial
/* * Copyright (C) 2015 IZITEQ B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package travel.izi.api.sample.util; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; import static android.location.LocationManager.NETWORK_PROVIDER; public final class Locations { @NonNull public static Location currentLocation(@NonNull Context context) { String locationProvider = NETWORK_PROVIDER; if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return new Location(locationProvider); } LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); return lastKnownLocation != null ? lastKnownLocation : new Location(locationProvider); } private Locations() { throw new AssertionError("No instances."); } }