0

私はアンドロイドのプログラミングが初めてで、アプリケーションに問題があります。私の 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 に答える