当我的位置经理和位置提供商可用时,我如何获得位置的价值?

时间:2014-04-25 08:11:26

标签: android

当我调试此代码时发现我的位置管理器和位置提供程序都有值但在onLocationChanged(位置位置)方法中没有获取位置值,那么我该如何解决这个问题。

public class MainActivity extends ActionBarActivity implements LocationListener
{   
EditText editText;
Button button;
Context context;
LocationManager locationManager;
private Location location12;
double longitude=0,latitude=0;
boolean gpsStatus=false,NetworkStatus=false,PassiveProvider=false;
private final long time=1000*10;//every 10 seconds 
private final float distance =5;//every 5 meter

String Provider=null;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addListenerAction();

}


public void addListenerAction()
    {
        editText=(EditText) findViewById(R.id.editText1);
        button=(Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) 
            {   
                context=getApplicationContext();
                getLocation();
            }
        });
    }

public void getLocation()
    {
        locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
        gpsStatus=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(gpsStatus)
        {
            Log.v("Gps is On","="+gpsStatus);
            Criteria criteria=new Criteria();
            Provider=locationManager.getBestProvider(criteria, true);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0,this);

    }
}
@Override
public void onLocationChanged(Location location) 
{
    location12=location;
    if(locationManager !=null && Provider !=null && location12 !=null)
    {
        Location s=location;
  // here i did not value. how may i resolve it.    
                  location=locationManager.getLastKnownLocation(Provider);

                if(s !=null)
                    {
                        latitude=location.getLatitude();
                        longitude=location.getLongitude();
                        System.out.println("lATITUDE ="+latitude + "Longitude ="+longitude);
                    }
    }

}


@Override
public void onProviderDisabled(String provider) {

}


@Override
public void onProviderEnabled(String provider) {


}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {


}
 }

我使用了这些权限。

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"/>

但我没有成功获得位置价值。

1 个答案:

答案 0 :(得分:0)

获得确切位置非常困难。如果您使用以下代码,那么您将获得精确位置。

需要做的事:

  1. 您需要拥有Google playservice Lib项目,该项目将在sdk示例中提供。

  2. 复制粘贴此类。

  3. public class Ex extends Activity实现了LocationListener,GooglePlayServicesClient.ConnectionCallbacks,       GooglePlayServicesClient.OnConnectionFailedListener {

    private Location location;
    private LocationRequest mLocationRequest;
    private LocationClient mLocationClient;
    
    private int UPDATE_INTERVAL_IN_MILLISECONDS = 0;
    private int FAST_INTERVAL_CEILING_IN_MILLISECONDS = 0;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 20000;
    
    
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.sample);
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
    
        mLocationClient = new LocationClient(this, this, this);
        mLocationClient.connect();
    
    
    }
    
    
    
    
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects. If the error
         * has a resolution, try sending an Intent to start a Google Play
         * services activity that can resolve error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult( this,CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            // If no resolution is available, display a dialog to the user with
            // the error.
    
        }
    }
    
    /*
     * This is overridden method of interface
     * GooglePlayServicesClient.ConnectionCallbacks which is called when
     * locationClient is connected to google service. You can receive GPS
     * reading only when this method is called.So request for location updates
     * from this method rather than onStart()
     */
    @Override
    public void onConnected(Bundle arg0) {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }
    
    @Override
    public void onDisconnected() {
        stopGPS();
    }
    
    /*
     * Overridden method of interface LocationListener called when location of
     * gps device is changed. Location Object is received as a parameter. This
     * method is called when location of GPS device is changed
     */
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            this.location=location;
            stopGPS();
        }
    }
    
    /*
     * Called when Service running in background is stopped. Remove location
     * Update to stop receiving GPS reading
     */
    public void stopGPS() {
        try{
            if(mLocationClient!=null){
                if(mLocationClient.isConnected()){
                    mLocationClient.removeLocationUpdates(this);
                    mLocationClient=null;
                }else{
                    mLocationClient=null;
                }
            }
            if(mLocationRequest!=null){
                mLocationRequest=null;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onDestroy() {
        stopGPS();
        super.onDestroy();
    }
    
    @Override
    public void onBackPressed() {
        stopGPS();
        super.onBackPressed();
    }
    }
    

    NOte:您需要Google Play服务库作为附加项目。启用GPS,然后启用Chenck,..和以下权限:

    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />