java 在没有互联网连接的情况下获取纬度和经度
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 在没有互联网连接的情况下获取纬度和经度相关的知识,希望对你有一定的参考价值。
// another way of implmenting using getLastKnowLocation.....
package com.sgs.bamp_app.fragment;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sgs.bamp_app.R;
import com.sgs.bamp_app.activity.FragmentTitleChangeListener;
import com.sgs.bamp_app.activity.NavigationUpdateActivity;
import com.sgs.bamp_app.data.local.BampDbHelper;
import com.sgs.bamp_app.model.BridgeSubmitData;
import com.sgs.bamp_app.service.LocationService;
import com.sgs.bamp_app.util.AppConstant;
import com.sgs.bamp_app.util.CommonClass;
import com.sgs.bamp_app.util.SharedPrefsHelper;
import com.sgs.bamp_app.util.SharedStaticData;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import static android.content.Context.LOCATION_SERVICE;
/**
* Created by manasa.bh on 10/27/2017.
*/
public class LocationShowFragment extends BaseFragment implements View.OnClickListener, CommonClass.OnBackPressedListener, LocationListener {
private TextView tvLongitude;
private TextView tvLatitude;
private TextView tvDate;
private TextView tvDateLabel;
private Button btNext;
private Button btBack;
private View view;
private String TAG = "LocationFragment";
private FragmentTitleChangeListener titleChangeListener;
private TextView textViewLatPostion1;
private TextView textViewLatPostion2;
private TextView textViewLatPostion4;
private TextView textViewLatPostion5;
private TextView textViewLatPostion6;
private TextView textViewLatPostion7;
private TextView textViewLatPostion8;
private TextView textViewLatPostion9;
private TextView textViewLatPostion10;
private TextView textViewLongPostion1;
private TextView textViewLongPostion2;
private TextView textViewLongPostion4;
private TextView textViewLongPostion5;
private TextView textViewLongPostion6;
private TextView textViewLongPostion7;
private TextView textViewLongPostion8;
private TextView textViewLongPostion9;
private TextView textViewLongPostion10;
private Button buttonReloadLocation;
private TextView textViewDateDots;
private BampDbHelper dbHelper;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 ; // 1 minute
protected LocationManager locationManager;
private String strLatitude;
private String strLongitude;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new BampDbHelper(getActivity());
/* Intent intent = new Intent(getActivity(), LocationService.class);
getActivity().startService(intent);*/
try {
titleChangeListener =(FragmentTitleChangeListener)getActivity();
String loginUser = SharedPrefsHelper.getInstance().get(AppConstant.KEY_USER_NAME,"");
if(loginUser != null) {
titleChangeListener.onExitListener();
titleChangeListener.onTitleChanged(AppConstant.BRIDGE_LOCATION_NUMBER,loginUser);
titleChangeListener.logOutListener();
}
}
catch (Exception e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.latlongscreen, container, false);
intialiseControls();
return view;
}
private void intialiseControls() {
tvLongitude = (TextView) view.findViewById(R.id.longvalue);
tvLatitude = (TextView) view.findViewById(R.id.latvalue);
tvDate = (TextView) view.findViewById(R.id.datevalue);
tvDateLabel = (TextView) view.findViewById(R.id.datetv);
btBack = (Button) view.findViewById(R.id.btBack);
btNext = (Button) view.findViewById(R.id.btNext);
buttonReloadLocation = (Button) view.findViewById(R.id.button_reload_location);
textViewDateDots = (TextView) view.findViewById(R.id.datedot);
textViewDateDots.setVisibility(View.GONE);
buttonReloadLocation.setVisibility(View.GONE);
btBack.setOnClickListener(this);
btNext.setOnClickListener(this);
tvDate.setVisibility(View.GONE);
tvDateLabel.setVisibility(View.GONE);
Location location = getLocation();
if(location != null) {
double lat = location.getLatitude();
strLatitude = String.valueOf(lat);
if (strLatitude != null) {
if (lat != 0.000000000) {
tvLatitude.setText(strLatitude);
SharedPrefsHelper.getInstance().save(AppConstant.KEY_SAVE_LAT, strLatitude);
}
else {
Toast.makeText(getActivity(), "Location is not Captured", Toast.LENGTH_SHORT).show();
}
}
else {
SharedPrefsHelper.getInstance().delete(AppConstant.KEY_SAVE_LAT);
}
double lon = location.getLongitude();
strLongitude = String.valueOf(lon);
if (strLongitude != null) {
if (lon != 0.000000000) {
tvLongitude.setText(strLongitude);
SharedPrefsHelper.getInstance().save(AppConstant.KEY_SAVE_LONG, strLongitude);
} else {
Toast.makeText(getActivity(), "Location is not Captured", Toast.LENGTH_SHORT).show();
}
} else {
SharedPrefsHelper.getInstance().delete(AppConstant.KEY_SAVE_LONG);
}
textViewLatPostion1 = (TextView) view.findViewById(R.id.tv_lat_long_1);
textViewLatPostion2 = (TextView) view.findViewById(R.id.tv_lat_long_2);
textViewLatPostion4 = (TextView) view.findViewById(R.id.tv_lat_long_4);
textViewLatPostion5 = (TextView) view.findViewById(R.id.tv_lat_long_5);
textViewLatPostion6 = (TextView) view.findViewById(R.id.tv_lat_long_6);
textViewLatPostion7 = (TextView) view.findViewById(R.id.tv_lat_long_7);
textViewLatPostion8 = (TextView) view.findViewById(R.id.tv_lat_long_8);
textViewLatPostion9 = (TextView) view.findViewById(R.id.tv_lat_long_9);
textViewLatPostion10 = (TextView) view.findViewById(R.id.tv_lat_long_10);
textViewLongPostion1 = (TextView) view.findViewById(R.id.tv_lat_long_11);
textViewLongPostion2 = (TextView) view.findViewById(R.id.tv_lat_long_12);
textViewLongPostion4 = (TextView) view.findViewById(R.id.tv_lat_long_14);
textViewLongPostion5 = (TextView) view.findViewById(R.id.tv_lat_long_15);
textViewLongPostion6 = (TextView) view.findViewById(R.id.tv_lat_long_16);
textViewLongPostion7 = (TextView) view.findViewById(R.id.tv_lat_long_17);
textViewLongPostion8 = (TextView) view.findViewById(R.id.tv_lat_long_18);
textViewLongPostion9 = (TextView) view.findViewById(R.id.tv_lat_long_19);
textViewLongPostion10 = (TextView) view.findViewById(R.id.tv_lat_long_20);
assert strLatitude != null;
try {
textViewLatPostion1.setText(String.valueOf(strLatitude.charAt(0)));
textViewLatPostion2.setText(String.valueOf(strLatitude.charAt(1)));
textViewLatPostion4.setText(String.valueOf(strLatitude.charAt(3)));
textViewLatPostion5.setText(String.valueOf(strLatitude.charAt(4)));
textViewLatPostion6.setText(String.valueOf(strLatitude.charAt(5)));
textViewLatPostion7.setText(String.valueOf(strLatitude.charAt(6)));
textViewLatPostion8.setText(String.valueOf(strLatitude.charAt(7)));
textViewLatPostion9.setText(String.valueOf(strLatitude.charAt(8)));
textViewLatPostion10.setText(String.valueOf(strLatitude.charAt(9)));
} catch (Exception e) {
e.printStackTrace();
}
assert strLongitude != null;
try {
textViewLongPostion1.setText(String.valueOf(strLongitude.charAt(0)));
textViewLongPostion2.setText(String.valueOf(strLongitude.charAt(1)));
textViewLongPostion4.setText(String.valueOf(strLongitude.charAt(3)));
textViewLongPostion5.setText(String.valueOf(strLongitude.charAt(4)));
textViewLongPostion6.setText(String.valueOf(strLongitude.charAt(5)));
textViewLongPostion7.setText(String.valueOf(strLongitude.charAt(6)));
textViewLongPostion8.setText(String.valueOf(strLongitude.charAt(7)));
textViewLongPostion9.setText(String.valueOf(strLongitude.charAt(8)));
textViewLongPostion10.setText(String.valueOf(strLongitude.charAt(9)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onResume() {
Log.d(TAG, "onResume: ");
try {
titleChangeListener =(FragmentTitleChangeListener)getActivity();
String loginUser = SharedPrefsHelper.getInstance().get(AppConstant.KEY_USER_NAME,"");
if(loginUser != null) {
titleChangeListener.onTitleChanged(AppConstant.BRIDGE_LOCATION_NUMBER,loginUser);
titleChangeListener.onExitListener();
titleChangeListener.logOutListener();
}
} catch (Exception e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
super.onResume();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btBack:
doBack();
break;
case R.id.btNext:
BridgeSubmitData bridgeSubmitData = new BridgeSubmitData();
NatinalIdentityFragment.isFirst = true;
if(strLatitude != null && strLongitude != null) {
bridgeSubmitData.setLatitude(strLatitude);
bridgeSubmitData.setLongitude(strLongitude);
boolean latLongInserted = dbHelper.firstLatLongLocation(bridgeSubmitData,"incomplete");
if(latLongInserted) {
CommonClass.displayFragment(mActivity, R.id.container, new BridgeClassificationFragment(), 2, null);
}
else {
Toast.makeText(mActivity, "wait for co-ordinates", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(mActivity, "wait for Co-ordinates", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
public void doBack() {
NatinalIdentityFragment.isFirst = false;
Log.d(TAG, "doBack: backCount before incrementing " + NatinalIdentityFragment.backCount);
NatinalIdentityFragment.backCount++;
Log.d(TAG, "doBack: backCount after incrementing " + NatinalIdentityFragment.backCount);
getActivity().getSupportFragmentManager().popBackStack();
}
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.GPS_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
showSettingsAlert();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
Log.d(TAG, "getLocation1: lat"+latitude);
longitude = location.getLongitude();
Log.d(TAG, "getLocation1: long"+longitude);
}
}
}
// 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();
Log.d(TAG, "getLocation2: lat"+latitude);
longitude = location.getLongitude();
Log.d(TAG, "getLocation2: long"+longitude);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
Log.d(TAG, "getLatitude: "+latitude);
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
Log.d(TAG, "getLongitude: "+longitude);
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Enable GPS");
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);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
double updateLatitude = location.getLatitude();
double updateLongitude = location.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(mContext, "Please enable GPS", Toast.LENGTH_SHORT).show();
showSettingsAlert();
}
@Override
public void onProviderEnabled(String provider) {
}
}
// add this in manifestFile
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION_CODE = 1;
private TextView textViewLat;
private TextView textViewLong;
private Button buttonReload;
private static final String TAG = "LocationService";
private Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute
protected LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewLat = findViewById(R.id.textViewLat);
textViewLong = findViewById(R.id.textViewLong);
buttonReload = findViewById(R.id.button);
getLocation();
buttonReload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getLocation();
}
});
}
private void getLocation() /*throws SecurityException*/ {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mylocation = locationmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_CODE);
}
} else
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateUI(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
showSettingsAlert();
}
});
}
private void updateUI(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
textViewLat.setText(String.valueOf(latitude));
textViewLong.setText(String.valueOf(longitude));
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Enable GPS");
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);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
// entire logic for geting the location with out using interent
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_CODE);
}
}
else
// write your logic here
// for any runtime permissions we can use the above code.......
以上是关于java 在没有互联网连接的情况下获取纬度和经度的主要内容,如果未能解决你的问题,请参考以下文章
如何在没有互联网连接的情况下在android中获取当前纬度和经度?
IPHONE:我可以在没有互联网的情况下使用 GPS 来获取当前的纬度和经度
在没有互联网的情况下在android上获取位置坐标(纬度和经度)