0

我是 android 编程新手,我的应用程序有问题。我的 Gps 只是不搜索位置或其他任何东西。是的,我的 GPS 已开启。清单包含许可:ACCESS_COARSE_LOCATION 和 ACCESS_FINE_LOCATION。

有人可以帮我吗?

public class LocationTest extends Activity implements
  LocationListener { 
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
     "high" };
private static final String[] S = { "out of service",
     "temporarily unavailable", "available" };

private LocationManager mgr;
private TextView output;
private String best;

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

  mgr = (LocationManager) getSystemService(LOCATION_SERVICE); 
  output = (TextView) findViewById(R.id.output);

  log("Location providers:");
  dumpProviders(); 

  Criteria criteria = new Criteria(); 
  best = mgr.getBestProvider(criteria, true);
  log("\nBest provider is: " + best);

  log("\nLocations (starting with last known):");
  if (best != null) {  
     Location location = mgr.getLastKnownLocation(best);
     dumpLocation(location);
  }
}

@Override
protected void onResume() {
  super.onResume();
  // Start updates (doc recommends delay >= 60000 ms)
  if (best != null) {
     mgr.requestLocationUpdates(best, 15000, 1, this);
  }
  }

 @Override
protected void onPause() {
  super.onPause();
  // Stop updates to save power while app paused
  mgr.removeUpdates(this);
}

public void onLocationChanged(Location location) {
  dumpLocation(location);
}

public void onProviderDisabled(String provider) {
  log("\nProvider disabled: " + provider);
}

public void onProviderEnabled(String provider) {
  log("\nProvider enabled: " + provider);
}

public void onStatusChanged(String provider, int status,
     Bundle extras) {
  log("\nProvider status changed: " + provider + ", status="
        + S[status] + ", extras=" + extras);
}

/** Write a string to the output window */
private void log(String string) {
  output.append(string + "\n");
}

/** Write information from all location providers */
private void dumpProviders() {
  List<String> providers = mgr.getAllProviders();
  for (String provider : providers) {
     dumpProvider(provider);
  }
}

/** Write information from a single location provider */
private void dumpProvider(String provider) {
  LocationProvider info = mgr.getProvider(provider);
  StringBuilder builder = new StringBuilder();
  builder.append("LocationProvider[")
        .append("name=")
        .append(info.getName())
        .append(",enabled=")
        .append(mgr.isProviderEnabled(provider))
        .append(",getAccuracy=")
        .append(A[info.getAccuracy() + 1])
        .append(",getPowerRequirement=")
        .append(P[info.getPowerRequirement() + 1])
        .append(",hasMonetaryCost=")
        .append(info.hasMonetaryCost())
        .append(",requiresCell=")
        .append(info.requiresCell())
        .append(",requiresNetwork=")
        .append(info.requiresNetwork())
        .append(",requiresSatellite=")
        .append(info.requiresSatellite())
        .append(",supportsAltitude=")
        .append(info.supportsAltitude())
        .append(",supportsBearing=")
        .append(info.supportsBearing())
        .append(",supportsSpeed=")
        .append(info.supportsSpeed())
        .append("]");
  log(builder.toString());
}

/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
  if (location == null)
     log("\nLocation[unknown]");
  else
     log("\n" + location.toString());
}

}
4

1 回答 1

0

我通常不这样做,但我几乎不得不去。这是我使用的代码,它有效。(只需将其放在一个新项目中)。我没有清理它,因为我从我的另一个项目中撕下了它,但是当你创建一个新项目并复制/粘贴它时它确实有效。:

import java.util.Timer;
import java.util.TimerTask;


import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;


public class MainActivity extends Activity {
    Timer timer1;
    LocationManager lm;
    boolean gps_loc = false;
    boolean gps_enabled=false;
    boolean network_enabled=false;
    double lat;
    double lng;
    String gps_location;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLocation(this, locationResult);
    }

    public LocationResult locationResult = new LocationResult() {
        public void gotLocation(final Location location) {
            try {
                lat = location.getLatitude();
                lng = location.getLongitude();
                if (lat != 0.0 && lng != 0.0) {
                    String sLat;
                    String sLng;
                    sLat = Double.toString(lat);
                    sLng = Double.toString(lng);
                    gps_location = sLat + " " + sLng;
                    Toast.makeText(getBaseContext(), "We got gps location!",
                            Toast.LENGTH_LONG).show();
                    System.out.println("We got gps");
                    System.out.println("lat = "+lat);
                    System.out.println("lng = "+lng);
                }
            } catch (Exception e) {

            }
        }
    };

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.

        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled){

          return false;
        }
        if(gps_enabled){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        }
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 35000);

        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
       @Override
        public void run() {

             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){

                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);

                 return;

             }
             locationResult.gotLocation(null);
        }

    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }

}

还要在清单中添加:

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

现在没有时间解释,如果你仍然需要它,也许明天。

它会在您的 logcat 中打印纬度和经度。

于 2012-11-13T15:38:11.787 回答