//这里是homeactivity.java上的按钮
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gps = new GpsTracker(DrAppointHome.this);
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,update).commit();
update.update(latitude, longitude);
// \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();
}
}
});
//这里是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);
if (!isGPSEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("TD", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("TD", "Lat: "+latitude);
}
}
}
}
}
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
try {
if (locationManager != null) {
locationManager.removeUpdates(GpsTracker.this);
}
}
catch (SecurityException e) {
e.printStackTrace();
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
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) {
}
@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;
}
}
//这里是java上的Request handlercode
public class RequestHandlerNearme {
List<String> sb;
List<DoctorNearMe> drList1 = new ArrayList<>();
public List<String> sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new ArrayList<>();
String response = "";
}
for (int i = 0; i<sb.size()-7; i=i+7){
drList1.add(new DoctorNearMe(sb.get(i),sb.get(i+1),sb.get(i+2),sb.get(i+3),sb.get(i+4),Double.parseDouble(sb.get(i+5)),Double.parseDouble(sb.get(i+6))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
//这里是java上的片段代码
public class DoctorNearYou extends Fragment {
private static final String NEAR_YOU_URL = "http://doctorsportal.netne.net/nearme.php";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private List<String> result;
ListView list;
public RequestHandlerNearme rh = new RequestHandlerNearme();
LayoutInflater inflater;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.inflater = inflater;
return inflater.inflate(R.layout.doctornearyoufragment,null);
}
public void update(final double latitude, final double longitude) {
rh.drList1.clear();
class TDsAdapter extends ArrayAdapter<DoctorNearMe> {
public TDsAdapter(){
super(getActivity().getApplicationContext(),R.layout.custom_list_view_near_me,rh.drList1);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = inflater.inflate(R.layout.custom_list_view_near_me, parent, false);
}
DoctorNearMe currentItem = rh.drList1.get(position);
TextView dRName = (TextView) itemView.findViewById(R.id.dRName1);
dRName.setText(currentItem.getDrName());
TextView drSpeciality = (TextView) itemView.findViewById(R.id.drSpeciality1);
drSpeciality.setText(currentItem.getDrSpeciality());
TextView drJobTitle = (TextView) itemView.findViewById(R.id.drJobTitle1);
drJobTitle.setText(currentItem.getDrJobTitle());
ImageView drProPic = (ImageView) itemView.findViewById(R.id.drPropic1);
Picasso.with(getContext()).load(currentItem.getDrProPic()).into(drProPic);
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(currentItem.getlatitude()-latitude);
double dLng = Math.toRadians(currentItem.getLongitude()-longitude);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(latitude)) * Math.cos(Math.toRadians(currentItem.getlatitude())) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
Double Distence = (Double) ((earthRadius * c)/1000);
TextView distence = (TextView) itemView.findViewById(R.id.drdistence);
distence.setText(Distence+"");
return itemView;
}
}
class LoadDoctors extends AsyncTask<Void, Void, List<String>>{
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(List<String> s) {
super.onPostExecute(s);
s.remove(s.size() - 1);
s.remove(s.size() - 1);
s.remove(s.size() - 1);
Toast.makeText(getActivity(), ""+s.size(), Toast.LENGTH_SHORT).show();
ArrayAdapter<DoctorNearMe> adapter = new TDsAdapter();
list = (ListView) getActivity().findViewById(R.id.drlistforhome1);
list.setAdapter(adapter);
}
@Override
protected List<String> doInBackground(Void... params) {
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_LATITUDE, latitude+"");
param.put(KEY_LONGITUDE, longitude+"");
result = rh.sendPostRequest(NEAR_YOU_URL, param);
return result;
}
}
new LoadDoctors().execute();
}
}
//这里是
的代码public class DoctorNearMe {
public String drName;
public String drSpeciality;
public String drJobTitle;
public String drProPic;
public String drUname;
public Double latitude;
public Double longitude;
public DoctorNearMe(String drName, String drSpeciality, String drJobTitle, String drProPic, String drUname, Double latitude, Double longitude) {
this.drName = drName;
this.drSpeciality = drSpeciality;
this.drJobTitle = drJobTitle;
this.drProPic = drProPic;
this.drUname = drUname;
this.latitude= latitude;
this.longitude=longitude;
}
public String getDrName() {
return drName;
}
public void setDrName(String drName) {
this.drName = drName;
}
public String getDrSpeciality() {
return drSpeciality;
}
public void setDrSpeciality(String drSpeciality) {
this.drSpeciality = drSpeciality;
}
public String getDrJobTitle() {
return drJobTitle;
}
public void setDrJobTitle(String drJobTitle) {
this.drJobTitle = drJobTitle;
}
public String getDrProPic() {
return drProPic;
}
public void setDrProPic(String drProPic) {
this.drProPic = drProPic;
}
public String getDrUname() {
return drUname;
}
public void setDrUname(String drUname) {
this.drUname = drUname;
}
public Double getlatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude= latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude= longitude;
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
if (!isGPSEnabled) {
// No network provider is enabled
} else { .... }
首先,您只使用gps提供商来获取位置,如果未启用GPS,则您的代码超出范围且永远不会发出位置请求。请注意代码的这种情况。
其次,当你调用getLocation()方法时,它可能无法获得新的位置,也许你知道。然后,您只获得gps提供程序的缓存位置。如果它没有缓存的位置数据,则在gps提供程序获得新位置之前,您的方法将返回null并且location参数将为null
我看到一些事情,每当你点击fab按钮就会创建GpsTracker,那么先前请求的位置更新呢?
为什么不在下面设置位置参数?
@Override
public void onLocationChanged(Location location) {
}
....
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
如果你不这样做,getLatitude和getLongitude会返回缓存值或null(指我的第二部分)