User Location
User Location
xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/get_loc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"/>
<TextView
android:id ="@+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude is " />
<TextView
android:id ="@+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude is " />
</LinearLayout>
MainActivity.java
package com.example.q1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get_loc = findViewById(R.id.get_loc);
latitude = findViewById(R.id.latitude);
longitude = findViewById(R.id.longitude);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
get_loc.setOnClickListener(new View.OnClickListener() {
@SuppressLint("MissingPermission")
@Override
public void onClick(View v) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(new
OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if(location != null)
{
latitude.setText("Latitude is
"+location.getLatitude());
longitude.setText("Longitude is
"+location.getLongitude());
}
}
});
}
});
}
}