如何在android中获取纬度和经度
我试图创建一个祈祷时间表应用程序,但当系统想要获取纬度和经度值时,我遇到了一个问题,在最初的程序中,我在主活动中设置了启用GPS的清单权限如何在android中获取纬度和经度,android,geocoding,Android,Geocoding,我试图创建一个祈祷时间表应用程序,但当系统想要获取纬度和经度值时,我遇到了一个问题,在最初的程序中,我在主活动中设置了启用GPS的清单权限 @Override public void onClick(View view) { if (ActivityCompat.checkSelfPermission(UtamaActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
@Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(UtamaActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(UtamaActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},44);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},44);
} else {
Intent jadwalSholat = new Intent(MainActivity.this, TimePrayActivity.class);
startActivity(jadwalSholat);
}
}
});
我已经在清单中添加了访问\u FINE和访问\u rough权限,但当进入活动时间祈祷时,GPS不会自动激活,用户必须手动激活GPS,即使GPS和互联网连接已激活,程序仍然无法获取纬度和经度值
时间活动:
public class JadwalSholatActivity extends AppCompatActivity {
...
FusedLocationProviderClient providerClient;
private double latitude, longitude;
private static final int ACCESS_LOCATION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jadwal_sholat);
...
providerClient = LocationServices.getFusedLocationProviderClient(this);
progressBar = findViewById(R.id.barbar);
checkState();
}
private void checkState(){
final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null){
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "Enable your GPS!", Toast.LENGTH_SHORT).show();
} else {
getLocation();
}
}
} else {
Toast.makeText(this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
private void getLocation(){
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
progressBar.setVisibility(View.VISIBLE);
providerClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null){
Geocoder geocoder = new Geocoder(JadwalSholatActivity.this,Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
latitude = (double) addresses.get(0).getLatitude();
longitude = (double) addresses.get(0).getLongitude();
jadwalSholat();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void jadwalSholat(){
progressBar.setVisibility(View.GONE);
DateComponents dateComponents = DateComponents.from(new Date());
**Coordinates coordinates = new Coordinates(latitude,longitude);**
CalculationParameters parameters = CalculationMethod.MUSLIM_WORLD_LEAGUE.getParameters();
SimpleDateFormat formats = new SimpleDateFormat("HH:mm");
formats.setTimeZone(TimeZone.getDefault());
PrayerTimes prayerTimes = new PrayerTimes(coordinates,dateComponents,parameters);
...
}
}
public类jadwalsholataactivity扩展了appcompativity{
...
FusedLocationProviderClient providerClient;
私人双纬度、经度;
专用静态最终int访问位置=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jadwal_sholat);
...
providerClient=LocationServices.getFusedLocationProviderClient(此);
progressBar=findViewById(R.id.barbar);
checkState();
}
私有void checkState(){
最终位置管理器位置管理器=(位置管理器)getSystemService(Context.LOCATION\u服务);
ConnectivityManager=(ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=manager.getActiveNetworkInfo();
if(networkInfo!=null){
if(networkInfo.getType()==ConnectivityManager.TYPE|WIFI | | networkInfo.getType()==ConnectivityManager.TYPE|MOBILE){
如果(!locationManager.isProviderEnabled(locationManager.GPS\U提供程序)){
Toast.makeText(这是“启用GPS!”,Toast.LENGTH_SHORT.show();
}否则{
getLocation();
}
}
}否则{
Toast.makeText(这是“没有Internet连接!”,Toast.LENGTH_SHORT.show();
}
}
私有void getLocation(){
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予
&&ActivityCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予){
返回;
}
progressBar.setVisibility(View.VISIBLE);
providerClient.getLastLocation().addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
位置=task.getResult();
如果(位置!=null){
Geocoder Geocoder=新的Geocoder(jadwalsholataActivity.this,Locale.getDefault());
试一试{
列表地址=geocoder.getFromLocation(location.getLatitude(),location.getLatitude(),1);
纬度=(双)地址。获取(0)。获取纬度();
经度=(双)地址。获取(0)。获取经度();
jadwalSholat();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
});
}
私有void jadwalSholat(){
progressBar.setVisibility(View.GONE);
DateComponents-DateComponents=DateComponents.from(new Date());
**坐标=新坐标(纬度、经度)**
CalculationParameters=CalculationMethod.MUSLIM_WORLD_LEAGUE.getParameters();
SimpleDataFormat格式=新的SimpleDataFormat(“HH:mm”);
formats.setTimeZone(TimeZone.getDefault());
祈祷时间祈祷时间=新祈祷时间(坐标、日期组件、参数);
...
}
}
因此,我遇到的问题很可能是,程序没有获得经度和纬度值,如果还有其他问题,请在注释中告诉他们
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)mContext, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// Show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// Check if GPS enabled
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
}
}
});
}
}
活动-AndroidGPSTrackingActivity.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)mContext, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// Show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// Check if GPS enabled
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
}
}
});
}
}
Layout-main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
调用了addOnCompleteListener
?如果是,您是否检查了任务是否成功<代码>任务。isSuccessful()?您想要接收位置更新还是仅接收最后位置?我想要的是用户的最后位置,我将尝试添加成功任务条件。谢谢