banner



How To Find Current Location In Android Studio

The simplest fashion to get the user'southward current location on Android


This example demonstrates how do I become the user's current location on android in the simplest mode.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Footstep two − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-viii"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"> <TextView    android:layout_marginTop="20dp"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="Get Current Location and City Name"    android:textAlignment="center"    android:layout_centerHorizontal="true"    android:textSize="20sp" /> <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/textView"    android:layout_centerInParent="true"    android:textSize="16sp"    android:textStyle="bold"/> </RelativeLayout>

Step three − Add the following dependency in Gradle

implementation 'com.google.android.gms:play-services-location:17.0.0'

Step iv − Add the following code to src/MainActivity.java

import androidx.notation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Geocoder; import android.location.Location; import android.os.Packet; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; public grade MainActivity extends AppCompatActivity {    private FusedLocationProviderClient fusedLocationClient;    private static final int LOCATION_PERMISSION_REQUEST_CODE = 2;    individual LocationAddressResultReceiver addressResultReceiver;    private TextView currentAddTv;    private Location currentLocation;    private LocationCallback locationCallback;    @Override    protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       addressResultReceiver = new LocationAddressResultReceiver(new Handler());       currentAddTv = findViewById(R.id.textView);       fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);       locationCallback = new LocationCallback() {          @Override          public void onLocationResult(LocationResult locationResult) {             currentLocation = locationResult.getLocations().go(0);             getAddress();          }       };       startLocationUpdates();    }    @SuppressWarnings("MissingPermission")    individual void startLocationUpdates() {       if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=       PackageManager.PERMISSION_GRANTED) {          ActivityCompat.requestPermissions(this, new          String[]{Manifest.permission.ACCESS_FINE_LOCATION},          LOCATION_PERMISSION_REQUEST_CODE);       }       else {          LocationRequest locationRequest = new LocationRequest();          locationRequest.setInterval(2000);          locationRequest.setFastestInterval(chiliad);          locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);          fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, zilch);       }    }    @SuppressWarnings("MissingPermission")    individual void getAddress() {       if (!Geocoder.isPresent()) {          Toast.makeText(MainActivity.this, "Can't find electric current accost, ",          Toast.LENGTH_SHORT).bear witness();          render;       }       Intent intent = new Intent(this, GetAddressIntentService.class);       intent.putExtra("add_receiver", addressResultReceiver);       intent.putExtra("add_location", currentLocation);       startService(intent);    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {    if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {          startLocationUpdates();       }        else {          Toast.makeText(this, "Location permission not granted, " + "restart the app if you want the          feature", Toast.LENGTH_SHORT).show();       }    } } private class LocationAddressResultReceiver extends ResultReceiver {    LocationAddressResultReceiver(Handler handler) {       super(handler);    }    @Override    protected void onReceiveResult(int resultCode, Parcel resultData) {       if (resultCode == 0) {          Log.d("Address", "Location aught retrying");          getAddress();       }       if (resultCode == 1) {          Toast.makeText(MainActivity.this, "Address not found, ", Toast.LENGTH_SHORT).bear witness();       }       String currentAdd = resultData.getString("address_result");          showResults(currentAdd);       }    }    private void showResults(String currentAdd) {       currentAddTv.setText(currentAdd);    }    @Override    protected void onResume() {       super.onResume();       startLocationUpdates();    }    @Override    protected void onPause() {       super.onPause();       fusedLocationClient.removeLocationUpdates(locationCallback);    } }        

Stride v − Create a new java class GetaddressIntentService.java and add the following code

parcel app.com.sample; import android.app.IntentService; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Parcel; import android.os.ResultReceiver; import android.util.Log; import java.util.List; import java.util.Locale; import java.util.Objects; import androidx.note.Nullable; public class GetAddressIntentService extends IntentService {    private static final Cord IDENTIFIER = "GetAddressIntentService";    private ResultReceiver addressResultReceiver;    public GetAddressIntentService() {       super(IDENTIFIER);    }    @Override    protected void onHandleIntent(@Nullable Intent intent) {       String msg;       addressResultReceiver = Objects.requireNonNull(intent).getParcelableExtra("add_receiver");       if (addressResultReceiver == null) {          Log.east("GetAddressIntentService", "No receiver, non processing the request further");          render;       }       Location location = intent.getParcelableExtra("add_location");       if (location == cipher) {          msg = "No location, can't go further without location";          sendResultsToReceiver(0, msg);       return;    }    Geocoder geocoder = new Geocoder(this, Locale.getDefault());    List<Address> addresses = null;    effort {       addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), ane);    }    catch (Exception ioException) {       Log.eastward("", "Error in getting accost for the location");    }    if (addresses == nada || addresses.size() == 0) {       msg = "No address found for the location";       sendResultsToReceiver(ane, msg);    }    else {       Address accost = addresses.get(0);       String addressDetails = address.getFeatureName() + "\n" + address.getThoroughfare() + "\northward" +       "Locality: " + accost.getLocality() + "\north" + "County: " + address.getSubAdminArea() + "\northward" +       "State: " + address.getAdminArea() + "\n" + "Land: " + address.getCountryName() + "\northward" +       "Postal Lawmaking: " + address.getPostalCode() + "\northward";       sendResultsToReceiver(two, addressDetails);    } } private void sendResultsToReceiver(int resultCode, String bulletin) {    Bundle packet = new Bundle();    parcel.putString("address_result", bulletin);    addressResultReceiver.send(resultCode, package);    } }        

Step half dozen − Add together the following code to androidManifest.xml

<?xml version="ane.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"    packet="app.com.sample">    <awarding       android:allowBackup="true"       android:icon="@mipmap/ic_launcher"       android:label="@cord/app_name"       android:roundIcon="@mipmap/ic_launcher_round"       android:supportsRtl="true"       android:theme="@mode/AppTheme">       <activity android:name=".MainActivity">          <intent-filter>             <action android:name="android.intent.action.MAIN" />             <category android:name="android.intent.category.LAUNCHER" />          </intent-filter>       </activeness>    <service android:name=".GetAddressIntentService" /> </awarding> <uses-permission android:proper name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:proper noun="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> </manifest>

Let's endeavor to run your awarding. I assume you have connected your bodily Android Mobile device with your calculator. To run the app from the android studio, open ane of your project's action files and click the RunPlay Icon icon from the toolbar. Select your mobile device as an option so check your mobile device which will brandish your default screen −

raja

Published on 25-Oct-2019 08:42:18

  • Related Questions & Answers
  • The simplest way to become the user'south current location on Android using Kotlin?
  • What's the simplest way to print a Java assortment?
  • How to get current GPS location programmatically on Android?
  • How to go the current GPS location programmatically on Android using Kotlin?
  • How to get current location in android web view?
  • How to get current location provider information in android?
  • How to show current location on a google map on Android?
  • How to get the Android Emulator's IP address?
  • How to get electric current location latitude and longitude in Android?
  • How to get current user is organisation user or not in android?
  • How to become the Tkinter widget's current x and y coordinates?
  • What is the simplest way to SSH using Python?
  • How to prove current location on a Google Map on Android using Kotlin?
  • How to get the Android device'southward primary eastward-mail address?
  • How to become the Android Emulator's IP address using Kotlin?

How To Find Current Location In Android Studio,

Source: https://www.tutorialspoint.com/the-simplest-way-to-get-the-user-s-current-location-on-android

Posted by: davisexter1987.blogspot.com

0 Response to "How To Find Current Location In Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel