【问题标题】:GPS doesn't search on my AndroidGPS 无法在我的 Android 上搜索
【发布时间】:2012-11-13 15:18:48
【问题描述】:

我是 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());
}

}

【问题讨论】:

  • 网络呢?他们是否在报告您的位置?您必须知道 GPS 传感器不会报告您在建筑物内的位置。他们只在户外工作。
  • .. 如果第一次运行它会花费很多时间。另请发布 Logcat 输出。
  • 回答了,我现在回家了,今天做的够多了,明天如果你还需要它会提供帮助(如果你愿意,我可以把这个项目明天下载)。
  • 事实上,这个应用程序在 2.3(Froyo) 版本上工作,但在我的 Jelly bean 或任何高于 Froyo 的版本上都不能工作,现在呢? =/

标签: android gps location


【解决方案1】:

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

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 中打印纬度和经度。

【讨论】:

  • 事实上,这个应用程序在 2.3(Froyo) 版本上工作,但在我的 Jelly bean 或任何高于 Froyo 的版本上都不能工作,现在呢? =/ 有人已经遇到过这样的问题了吗?
  • @KleberRibeiro 它适用于我的(4.0.4),它是否给出任何具体错误?我将很快再次在手机上进行测试。当我感觉在睡觉时,我的手机掉进了浴缸:p。需要先解决这个问题。
  • 没有错误,GPS只是不搜索,你知道屏幕顶部出现的图标吗?所以,它没有出现
  • @KleberRibeiro 所以也没有消息(在电话上)“我们有 gps”。尝试调试程序停止的位置,因为它对我有用。在 2.3.3 和 4.0.4
  • 我认为你不理解。程序永远不会停止,他只是不搜索信息,因此,屏幕顶部的图标不会出现。在一部手机中它会搜索,而在另一部手机中则不会。
猜你喜欢
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多