2014-10-08 217 views
0

在我的应用程序中,我有一个对话框。点击是时,它发送一个以纬度和经度为参数的HTTP请求。截至目前,该应用程序从GPS_PROVIDER中检索这些信息,但如果GPS不可用,我希望它能从3G和WiFi获取坐标。 有人可以帮忙吗?从3G/WiFi获取坐标

AlertDialog ad = new AlertDialog.Builder(getActivity()).setTitle("Dialog title") 
       .setMessage("Do you want to send a request?") 
       .setPositiveButton("Yes", 
         new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         if (locationManager 
           .isProviderEnabled(LocationManager.GPS_PROVIDER) && location!=null) { 
//do HTTP request stuff 
           if (isOnline()) { 

           if (response.getStatusLine().getStatusCode()==200) { 
            Toast toast = Toast.makeText(getActivity(), "Request has been sent. Your coordinates are: " + Double.toString(location.getLatitude()) + " (Latitude) " + Double.toString(location.getLongitude()) + " (Longitude).", Toast.LENGTH_LONG); 
            toast.show(); 
           } 
           else { 
            Toast toast = Toast.makeText(getActivity(), "Request has NOT been sent.", Toast.LENGTH_LONG); 
            toast.show(); 
           } 
          } 
          else { 
           Toast toast = Toast.makeText(getActivity(), "Network is not available.", Toast.LENGTH_LONG); 
           toast.show(); 
          } 
         } 
         else { 
          Toast toast = Toast.makeText(getActivity(), "GPS is not available.", Toast.LENGTH_LONG); 
          toast.show(); 
         } 
        } 
       }).setNegativeButton("No", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         Toast toast = Toast.makeText(getActivity(), "Request has not been sent.", Toast.LENGTH_LONG); 
         toast.show(); 
        } 
       }).create(); 
     ad.show(); 
} 
public boolean isOnline() { 
    ConnectivityManager cm = 
      (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 

    return cm.getActiveNetworkInfo() != null && 
      cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
} 

回答

0

花花公子u可以使用这个

private Location getLocation() { 
    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
     return manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
     return manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    } 
    return null; 
} 

对于使用基于唯一的网络位置使用一个

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

对于基于GPS的位置,这一个

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
+0

谢谢!很有帮助。 – user3673449 2014-10-08 13:54:13