We have a requirement to get current location coordinates in our app. For getting current location coordinates, basically we will use GPS or Internet Providers. But now I am using Google play services to get coordinates. Google Play services provides a new FusedLocationProvider. This provider included both Internet and GPS APIs. Fused Location Provider automatically select best method of ascertaining the user's location: either WiFi or GPS. Its also very easy to use, but we'll need to make sure we have the Google Play Services support library and add it to our Gradle build file.
Screen Shots:
Download Source Code
Step 1:
Open activity_main.xml file and copy below code.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.prasad.currentlocationex.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Current Location" android:textColor="@color/colorPrimary" android:textSize="22dp" /> <TextView android:id="@+id/lat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Latutude:" android:textColor="#000000" android:textSize="18dp" /> <TextView android:id="@+id/lng" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Longitude:" android:textColor="#000000" android:textSize="18dp" /> <Button android:id="@+id/getLocation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="10dp" android:text="Get Location" /> </LinearLayout>
Step 2:
Open build.gradle (app) file and add 'com.google.android.gms:play-services:8.4.0' library in dependencies and sync that library.
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.google.android.gms:play-services:8.4.0' }
Step 3:
Crate "GetCurrentLocation.Java" class file and copy the below code.
package com.liquitrac.certificategeneration.utils; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; import pub.devrel.easypermissions.EasyPermissions; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; /** * Created by venkataprasad.kukka on 10-08-2016. */ public class GetCurrentLocation implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { public static final String TAG = "GetCurrentLocation"; public GoogleApiClient mGoogleApiClient; public LocationRequest mLocationRequest; public Location mLastLocation; public String latitude, longitude; private final int REQUEST_CHECK_SETTINGS = 300; Activity context; public GetCurrentLocation(Activity activity) { context = activity; buildGoogleApiClient(); createLocationRequest(); } public void connectGoogleApi() { if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } public void disConnectGoogleApi() { if (mGoogleApiClient != null) { if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(10000); mLocationRequest.setFastestInterval(5000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // for enable device location LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); final LocationSettingsStates LS_state = locationSettingsResult.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } @Override public void onConnected(@Nullable Bundle bundle) { getCurrentLocation(); } public void getCurrentLocation() { if (checkPermission()) { mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation == null) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } else { latitude = String.format("%f", mLastLocation.getLatitude()); longitude = String.format("%f", mLastLocation.getLongitude()); if (!TextUtils.isEmpty(latitude) || !TextUtils.isEmpty(longitude)) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } } else { requestPermission(); } } private boolean checkPermission() { int result1 = ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION); int result2 = ContextCompat.checkSelfPermission(context, ACCESS_COARSE_LOCATION); return result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED; } private void requestPermission() { ActivityCompat.requestPermissions(context, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 100); } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult result) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onLocationChanged(Location location) { if (mGoogleApiClient != null) { if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) { mGoogleApiClient.disconnect(); mGoogleApiClient.connect(); } else if (!mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } } }
Step 4:
Open MainActivity.Java class and copy below code.
package com.prasad.currentlocationex; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView latitudeView, longitudeView; private Button getLocationBtn; GetCurrentLocation currentLoc; private String latitude, longitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initControls(); currentLoc = new GetCurrentLocation(this); } private void initControls() { latitudeView = (TextView) findViewById(R.id.lat); longitudeView = (TextView) findViewById(R.id.lng); getLocationBtn = (Button) findViewById(R.id.getLocation); getLocationBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { latitude = currentLoc.latitude; longitude = currentLoc.longitude; if (TextUtils.isEmpty(latitude) || TextUtils.isEmpty(longitude)) { latitude = "0.00"; longitude = "0.00"; } latitudeView.setText("Latitude: " + latitude); longitudeView.setText("Longitude: " + longitude); } }); } @Override protected void onResume() { super.onResume(); currentLoc.connectGoogleApi(); } @Override protected void onStop() { super.onStop(); currentLoc.disConnectGoogleApi(); } }
Step 5:
open AndroidManifest.xml file and add the below permissions.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.prasad.currentlocationex"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
No comments:
Post a Comment