在Android应用程序中获取当前纬度和经度

时间:2012-01-10 05:11:15

标签: android latitude-longitude

我尝试通过以下链接获取纬度和经度而不使用onLocationChanged。但是我得到了UnKnown Error。为什么会出现此错误? find current location latitude and longitude

import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {
    final DBAdapter1 db=new DBAdapter1(this);
    private ConnectivityReceiver receiver = null;
    private TextView txtNetworkInfo ;
    private static TextView latituteField;
    private static TextView longitudeField;
    private LocationManager locationManager;
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    private static final String HostUrl =" http://yyy/Service.svc";
    // private static final String HostUrl ="  http://xxxx/Service.svc";
    private static final String NAMESPACE = "http://tempuri.org/";
    private HttpTransportSE httpTransport = new HttpTransportSE(HostUrl);
    private String provider;
    private SoapObject request=null;
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1800000; // in Milliseconds
    String str;
    String str2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the location provider -> use
        // default
        Criteria criteria = new Criteria();
        Log.i("ConnTest",locationManager.toString());
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            float lat = (float) (location.getLatitude());
            float lng = (float) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
            final   double  a=(int) (location.getLatitude() * 1E6);
            final  double  b=(int) (location.getLongitude() * 1E6);
            str = Double.toString(a);
            str2=Double.toString(b);

        } else {
            latituteField.setText("provider not available");
            longitudeField.setText("provider not available");
        }

        txtNetworkInfo = (TextView)findViewById(R.id.txtNetworkInfo);

        receiver = new ConnectivityReceiver();

        registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //locationManager.requestLocationUpdates(provider,1000, 1, this);
        locationManager.requestLocationUpdates(
                provider, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                this
        );
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        float lat = (float) (location.getLatitude());
        float lng = (float) (location.getLongitude());
        longitudeField.setText(String.valueOf(lng));
        latituteField.setText(String.valueOf(lat));

        Log.e("344444444444:",str);
        Toast.makeText(getBaseContext(), 
                    "Latitude: " + str,

                    Toast.LENGTH_SHORT).show();
         try {
                db.open();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             long id=db.insert(latituteField.getText().toString(),longitudeField.getText().toString());
                if(id>1)
                    {
                    Toast.makeText(getBaseContext(),"one record is inserted",Toast.LENGTH_LONG).show();
                    }
                else
                {
                    Toast.makeText(getBaseContext(),"not inserted",Toast.LENGTH_LONG).show();

                }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Disenabled provider " + provider,
                Toast.LENGTH_SHORT).show();

    }
    protected void Display(Cursor c) {
        Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
         "Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
         Toast.LENGTH_LONG, 0).show();    
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);

        super.onDestroy();
    }

    private String getNetworkStateString(NetworkInfo.State state){
        String stateString = "Unknown";

        switch(state)
        {
            case CONNECTED:         stateString = "Connected";              break;
            case CONNECTING:        stateString = "Connecting";     break;
            case DISCONNECTED:      stateString = "Disconnected";   break;
            case DISCONNECTING:     stateString = "Disconnecting";  break;
            case SUSPENDED:         stateString = "Suspended";              break;
            default:                        stateString = "Unknown";                break;
        }

        return stateString;
    }

    private class ConnectivityReceiver extends BroadcastReceiver{

        private Timer mTimer;
        private TimerTask mTimerTask;

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

            if(null != info)
            {
                    String state = getNetworkStateString(info.getState());
                    if(state.equals("Connected")){
                        mTimer = new Timer();
                        mTimerTask = new TimerTask() {
                            @Override
                            public void run() {
                                MainActivity.this.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {

                                        //Toast.makeText(getBaseContext(), "Disenabled provider " + provider,
                                                ///Toast.LENGTH_SHORT).show();  
                                        result();
                                    }
                                });
                           }
                        };
                        mTimer.scheduleAtFixedRate(mTimerTask,180000,180000);
                    }
                }
            }   
        }

    private void result() {
        SoapPrimitive response=null;
         final String methodname="InsertAllGPSInformation";
            request = new SoapObject(NAMESPACE,methodname);
            envelope.dotNet = true;
            TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String getImeNumber=telephonyManager.getDeviceId();
            SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String newtime =  sdfDateTime.format(new Date(System.currentTimeMillis()));
            request.addProperty("IMEINumber","0");
            request.addProperty("Longitude",str); 
            request.addProperty("Latitude",str2); 
            request.addProperty("Date",newtime);

            envelope.setOutputSoapObject(request);
            String result = null;
            try
             {          
                httpTransport.call(NAMESPACE+"IService/"+methodname, envelope);
                response = ( SoapPrimitive )envelope.getResponse();
                result=response.toString();
             }
            catch(Exception e)
             {
                Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
                Log.e("Upload Picture Error:",e.getMessage());
             }
            if(result.equals("Saved Successfully")){
            Toast.makeText(getBaseContext(), ""+result, Toast.LENGTH_LONG).show();
            }
        }
    }

3 个答案:

答案 0 :(得分:2)

使用android实际上很容易从GPS服务获取位置。使用LocationManager最简单的方法来执行此操作

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

customLocationListener = new CustomLocationListener();

locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER,
        0,
        0,
        ll);

....一个Spagehtti代码在这里.......

class CustomLocationListener implements LocationListener{ ............
      public void onLocationChanged(Location argLocation) { 
         if(location != null) {     
        int latitude=(int)(argLocation.getLatitude()*1E6);
        int longitude=(int)(argLocation.getLongitude()*1E6);
              }
       } ........ }

也可能会检查Location Android API和Android Development

答案 1 :(得分:0)

//The code in my project:

private void GetLocation(){
           // NETWORK
    if (null == location && WeiboApplication.isNetworkAvailable(pContext)) {
        location = getLocationWifi(pContext);
    }

    // Cell
    if (null == location && WeiboApplication.isNetworkAvailable(pContext)) {
        location = getLocationStation(pContext);
        /*WifiInfoManager wm=new WifiInfoManager();
        CellIdInfoManager cellID=new CellIdInfoManager();
        location=callGear(wm.getWifiInfo(pContext), cellID.getCellIDInfo(pContext));*/
    }

    // GPS
    if (WeiboApplication.isGpsAvailable(pContext)) {
        location = getLocationGPS(pContext);
    }
}


/**
 * GetAddressByLocaion   * 
 * @param location
 * @return
 */
public static void doLocationName(Location location, Context pContext) {

    if (null != location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        List<Address> addList = null;

        addList = getLocationGoogleAPI(lat, lng, 1);

        if (null == addList || addList.size() == 0) {
            addList = getLocationGeocoderAPI(lat, lng, 1, pContext);
        }
        if (addList != null && addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Address ad = addList.get(i);
                locationName = ad.getLocality(); 
                if (ad.getThoroughfare() != null) {
                    locationName = locationName + ad.getThoroughfare();
                }
            }
        }
    } else {
        locationName = "";
    }
}

private static List<Address> getLocationGeocoderAPI(double lat, double lon, int maxResults, Context pContext) {

    List<Address> results = new ArrayList<Address>();

    try {
        Geocoder ge = new Geocoder(pContext, Locale.getDefault());
        results = ge.getFromLocation(lat, lon, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return results;
}

/**
 * GetAddress ByLocation(Http)
 * 
 * @param lat
 * @param lon
 * @param maxResults
 * @return
 */
private static List<Address> getLocationGoogleAPI(double lat, double lon, int maxResults) {
    String urlStr = "http://maps.google.com/maps/geo?q=" + lat + "," + lon + "&output=json&sensor=true";
    String response = "";
    List<Address> results = new ArrayList<Address>();
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
    HttpConnectionParams.setSoTimeout(httpParams, 2000);
    HttpClient client = new DefaultHttpClient(httpParams);

    try {
        HttpResponse hr = client.execute(new HttpGet(urlStr));
        HttpEntity entity = hr.getEntity();
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        String buff = null;
        while ((buff = br.readLine()) != null)
            response += buff;

    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONArray responseArray = null;
    try {
        JSONObject jsonObject = new JSONObject(response);
        responseArray = jsonObject.getJSONArray("Placemark");
    } catch (JSONException e) {
        return results;
    }

    for (int i = 0; i < responseArray.length() && i < maxResults; i++) {
        Address addy = new Address(Locale.getDefault());
        try {
            JSONObject jsl = responseArray.getJSONObject(i);
            jsl = jsl.getJSONObject("AddressDetails").getJSONObject("Country").getJSONObject("AdministrativeArea")
                    .getJSONObject("Locality");
            String locality = null;
            if (jsl.getString("LocalityName") == null) {
                locality = null;
            } else {
                locality = jsl.getString("LocalityName");
            }
            if (jsl.getJSONObject("DependentLocality").getString("DependentLocalityName") != null) {
                locality = locality + jsl.getJSONObject("DependentLocality").getString("DependentLocalityName");
                ;
            }
            addy.setLocality(locality);
            addy.setThoroughfare(jsl.getJSONObject("DependentLocality").getJSONObject("Thoroughfare")
                    .getString("ThoroughfareName"));

        } catch (JSONException e) {
            e.printStackTrace();
            results.add(addy);
            continue;
        }

        results.add(addy);
    }
    return results;
}

/**
 * GetLocaionbyGPS
 * 
 * @return
 */
private static Location getLocationGPS(Context pContext) {
    LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String locationProvider = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(locationProvider);

    // location=locationManager.requestLocationUpdates(locationProvider,
    // 30000, 10,new GpsLocationListener());

    return location;
}

/**
 * GetLocaionByWifi
 * 
 * @param context
 * @return
 */
private static Location getLocationWifi(Context pContext) {
    Location location = null;
    try {
        LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
        WifiManager wifiManager = (WifiManager) pContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
            System.out.println("------------location INFO:" + location);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}

/**
 * getLocaionByCell
 * 
 * @param context
 * @return
 */
private static Location getLocationStation(Context pContext) {
    TelephonyManager tm = (TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE);
    try {
        if ((String) getNetType(pContext) != "UNKNOWN"&& ((String) getNetType(pContext) == "HSDPA" || getNetType(pContext) == "HSPA")) {// 3G
            location = null;
            GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
            if (gcl == null) {
                return null;
            }
            int cid = gcl.getCid();
            int lac = gcl.getLac();
            int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
            int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
            try {
                // JSON
                JSONObject holder = new JSONObject();
                holder.put("version", "1.1.0");
                holder.put("host", "maps.google.com");
                holder.put("address_language", "zh_CN");
                holder.put("request_address", true);

                JSONArray array = new JSONArray();
                JSONObject data = new JSONObject();
                data.put("cell_id", cid); // 25070
                data.put("location_area_code", lac);// 4474
                data.put("mobile_country_code", mcc);// 460
                data.put("mobile_network_code", mnc);// 0
                data.put("radio_type","gsm");
                array.put(data);
                holder.put("cell_towers", array);

                // hTTP
                DefaultHttpClient client = new DefaultHttpClient();


                String host=Proxy.getDefaultHost();
                HttpPost post = new HttpPost("http://www.google.com/loc/json");
                if (host!=null) {
                    int port = Proxy.getDefaultPort();
                    HttpHost httpHost=new HttpHost(host, port);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
                }

                StringEntity se = new StringEntity(holder.toString());
                post.setEntity(se);
                HttpResponse resp = client.execute(post);
                HttpEntity entity = resp.getEntity();
                InputStream is = entity.getContent();
                if (is == null) {
                    return null;
                }
                String jsonStr = JSONProvider.convertStreamToString(is);
                if (jsonStr == null) {
                    return null;
                }
                JSONObject jsonObject = new JSONObject(jsonStr);
                JSONObject jsonLocation = jsonObject.getJSONObject("location");
                if (jsonLocation != null) {
                    String latitude = jsonLocation.getString("latitude");
                    String longitude = jsonLocation.getString("longitude");
                    location = new Location(AppLocation.class.getName());
                    location.setLatitude(Double.parseDouble(latitude));
                    location.setLongitude(Double.parseDouble(longitude));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "UTMS") {
            location_cdma = null;
            location = null;
            location_cdma = (CdmaCellLocation) tm.getCellLocation();// cdma
            if (location_cdma != null) {
                try {
                    int sid = location_cdma.getSystemId();
                                                            // mobileNetworkCode
                    int bid = location_cdma.getBaseStationId(); 
                                                                // cellId
                    int nid = location_cdma.getNetworkId();
                                                            // locationAreaCode

                    double CdmaLat = (double) location_cdma.getBaseStationLatitude() / 14400;
                    double CdmaLon = (double) location_cdma.getBaseStationLongitude() / 14400;

                                            // json                     JSONObject holder = new JSONObject();
                    holder.put("version", "1.1.0");
                    holder.put("host", "maps.google.com");
                    holder.put("address_language", "zh_CN");
                    holder.put("radio_type", "cdma");
                    holder.put("request_address", true);

                    JSONArray array = new JSONArray();
                    JSONObject data = new JSONObject();
                    data.put("cell_id", bid); // 25070
                    data.put("location_area_code", nid);// 4474
                    data.put("mobile_country_code", 460);// 460
                    data.put("mobile_network_code", sid);// 0
                    array.put(data);
                    holder.put("cell_towers", array);

                    // http
                    DefaultHttpClient client = new DefaultHttpClient();

                    String host=Proxy.getDefaultHost();
                    HttpPost post = new HttpPost("http://www.google.com/loc/json");
                    if (host!=null) {
                        int port = Proxy.getDefaultPort();
                        HttpHost httpHost=new HttpHost(host, port);
                        client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
                    }




                    StringEntity se = new StringEntity(holder.toString());
                    post.setEntity(se);
                    HttpResponse resp = client.execute(post);
                    HttpEntity entity = resp.getEntity();
                    InputStream is = entity.getContent();
                    if (is == null) {
                        return null;
                    }
                    String jsonStr = JSONProvider.convertStreamToString(is);
                    if (jsonStr == null) {
                        return null;
                    }
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    JSONObject jsonLocation = jsonObject.getJSONObject("location");
                    if (jsonLocation != null) {
                        String latitude = jsonLocation.getString("latitude");
                        String longitude = jsonLocation.getString("longitude");

                        location = new Location(AppLocation.class.getName());
                        location.setLatitude(Double.parseDouble(latitude));
                        location.setLongitude(Double.parseDouble(longitude));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "GPRS") {
            location = null;
            GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
            int cid = gcl.getCid();
            int lac = gcl.getLac();

            int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
            int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
            try {
                // JSON
                JSONObject holder = new JSONObject();
                holder.put("version", "1.1.0");
                holder.put("host", "maps.google.com");
                holder.put("address_language", "zh_CN");
                holder.put("request_address", true);

                JSONArray array = new JSONArray();
                JSONObject data = new JSONObject();
                data.put("cell_id", cid); // 25070
                data.put("location_area_code", lac);// 4474
                data.put("mobile_country_code", mcc);// 460
                data.put("mobile_network_code", mnc);// 0
                array.put(data);
                holder.put("cell_towers", array);

                                    DefaultHttpClient client = new DefaultHttpClient();


                String host=Proxy.getDefaultHost();
                HttpPost post = new HttpPost("http://www.google.com/loc/json");
                if (host!=null) {
                    int port = Proxy.getDefaultPort();
                    HttpHost httpHost=new HttpHost(host, port);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
                }



                StringEntity se = new StringEntity(holder.toString());
                post.setEntity(se);
                HttpResponse resp = client.execute(post);
                HttpEntity entity = resp.getEntity();
                InputStream is = entity.getContent();
                if (is == null) {
                    return null;
                }
                String jsonStr = JSONProvider.convertStreamToString(is);
                if (jsonStr == null) {
                    return null;
                }
                JSONObject jsonObject = new JSONObject(jsonStr);
                JSONObject jsonLocation = jsonObject.getJSONObject("location");
                if (jsonLocation != null) {
                    String latitude = jsonLocation.getString("latitude");
                    String longitude = jsonLocation.getString("longitude");
                    location = new Location(AppLocation.class.getName());
                    location.setLatitude(Double.parseDouble(latitude));
                    location.setLongitude(Double.parseDouble(longitude));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "EDGE") {
            location = null;
            GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
            int cid = gcl.getCid();
            int lac = gcl.getLac();

            int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
            int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
            try {
                // Build json string which is used to search something
                JSONObject holder = new JSONObject();
                holder.put("version", "1.1.0");
                holder.put("host", "maps.google.com");
                holder.put("address_language", "zh_CN");
                holder.put("request_address", true);

                JSONArray array = new JSONArray();
                JSONObject data = new JSONObject();
                data.put("cell_id", cid); // 25070
                data.put("location_area_code", lac);// 4474
                data.put("mobile_country_code", mcc);// 460
                data.put("mobile_network_code", mnc);// 0
                array.put(data);
                holder.put("cell_towers", array);

                // create connection, send request then receive response
                DefaultHttpClient client = new DefaultHttpClient();

                String host=Proxy.getDefaultHost();
                HttpPost post = new HttpPost("http://www.google.com/loc/json");
                if (host!=null) {
                    int port = Proxy.getDefaultPort();
                    HttpHost httpHost=new HttpHost(host, port);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
                }



                StringEntity se = new StringEntity(holder.toString());
                post.setEntity(se);
                HttpResponse resp = client.execute(post);
                HttpEntity entity = resp.getEntity();
                InputStream is = entity.getContent();
                if (is == null) {
                    return null;
                }
                String jsonStr = JSONProvider.convertStreamToString(is);
                if (jsonStr == null) {
                    return null;
                }
                JSONObject jsonObject = new JSONObject(jsonStr);
                JSONObject jsonLocation = jsonObject.getJSONObject("location");
                if (jsonLocation != null) {
                    String latitude = jsonLocation.getString("latitude");
                    String longitude = jsonLocation.getString("longitude");
                    location = new Location(AppLocation.class.getName());
                    location.setLatitude(Double.parseDouble(latitude));
                    location.setLongitude(Double.parseDouble(longitude));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;

}

我希望我能帮到你。

答案 2 :(得分:0)

implementation 'com.google.android.gms:play-services-location:11.6.0'

活动中:

double latitude, longitude;
LocationManager locationManager;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getLocation()
}

void getLocation() {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //GlobalToast.toastMessage(this, "please provide location permission.");
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 400, this);
        } else {
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (isGPSEnabled) {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 400, this);
            }
        }
    }    


 @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("location", "change");

        Log.d("latitude", String.valueOf(latitude));
        Log.d("longitude", String.valueOf(longitude));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {
        Toast.makeText(getApplicationContext(), "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }