我目前正在开发一款Android应用,它会提示用户启用GPS,如果它没有打开,我已经将AlertDialog用于此目的。从设置启用GPS并按回按钮返回我的应用程序后,mapView不会反映我当前的位置。虽然如果我在运行应用程序之前打开GPS,应用程序会正确显示我的位置。我想知道在启用GPS目的后用于此刷新用户位置的方法。任何相关的文章都会有所帮助。
以下是我的GPS部分代码:
GPSTracker.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;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude 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/Wi-Fi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the 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 the 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;
}
}
以下类使用上面的类来显示mapView中的位置
LocationActivity.java
public class LocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
AppLocationService appLocationService;
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
//Google maps implementation
GoogleMap googleMap;
private static final String TAG = LocationActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
createMapView();
btnShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnSendAddress = (Button) findViewById(R.id.btnSendAddress);
gps = new GPSTracker(LocationActivity.this);
// Check if GPS enabled and if enabled after popup then call same fn
MapMyCurrentLoction();
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MapMyCurrentLoction();
}
});
btnSendAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tag_string_req_send_data = "req_send";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_AUTOWALA_DHUNDO, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Autowala Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
Log.d("Autowale ka data","success");
} else {
// Error occurred in data sending. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Data sending Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data_send");
params.put("latitude", Double.toString(gps.getLatitude()));
params.put("longitude", Double.toString(gps.getLongitude()));
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req_send_data);
}
});
}
@Override
protected void onPause(){
super.onPause();
MapMyCurrentLoction();
//super.onResume();
}
@Override
protected void onResume(){
super.onResume();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
//super.onResume();
}
private void createMapView(){
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map",Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
/**
* Adds a marker to the map
*/
private void addMarker(double lat,double lng){
/** Make sure that the map has been initialised **/
if(null != googleMap){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.title("Your Location")
.draggable(true)
);
//zooming to my location
float zoomLevel = 16.0F; //This goes up to 21
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, zoomLevel);
googleMap.animateCamera(yourLocation);
}
}
private void MapMyCurrentLoction(){
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
/*------- To get city name from coordinates -------- */
String area = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addressList = null;
try {
addressList = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
area = sb.toString();
}
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\n"+area, Toast.LENGTH_SHORT).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
//Again search and map my location after enabling gps
}
}
}
答案 0 :(得分:0)
你可能对“onResume&#39;方法。回到Activity后,调用了一个。 Sho在那里你应该更新位置
答案 1 :(得分:0)
您只需要初始化
gps = new GPSTracker(LocationActivity.this);
在onResume()和onCreate()上,如果需要,那么在onRestart()上也是如此。 这不是正确的方法,但为了使其正常工作,你可以做到这一点。