I am not able to get the location of the user in android studio. I have choosed Java as my backend language. I need an alternative way to get the location of the user instead of fusedlocation, but I am not able to implement it in my project. Please help me with the code that I should use in my project for getting the location.
My Backend Code -
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button getLocationBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocationBtn = findViewById(R.id.getLocationBTN);
getLocationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLocation();
}
});
}
private void getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(this, "Latitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to get location", Toast.LENGTH_SHORT).show();
}
}
}
I tried with fused location but its not working in my case. I need the code which used other method to get the current location of user instead of fusedlocation.