通过GPS或网络获取Android当前位置

时间:2015-04-08 07:58:00

标签: java android

我想获取当前位置并使用纬度和经度计算一些数据。我的代码在某些情况下有效,但在其他情况下无效。

public class Show_gheble extends Activity implements SensorEventListener {

protected Double mylatitude,mylongitude;
boolean set_location=false;
boolean set_angel=false;
private SensorManager mSensorManager;

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

    image=(ImageView) findViewById(R.id.imageView1);
    image1=(ImageView) findViewById(R.id.imageView2);

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

    String provider = LocationManager.GPS_PROVIDER;
    String provider2 = LocationManager.NETWORK_PROVIDER;

    Location location = locationManager.getLastKnownLocation(provider);
    Location location2 = locationManager.getLastKnownLocation(provider2);

    updateWithNewLocation(location,location2);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}

private void updateWithNewLocation(Location location,Location location2) {

String latLongString;

if (location != null) {
    mylatitude = location.getLatitude();
    mylongitude = location.getLongitude();

    makkeh_ang=get_angel(mylatitude, mylongitude);
    set_angel=true;
}
else if(location2 != null)
{
    mylatitude = location2.getLatitude();
    mylongitude = location2.getLongitude();
    makkeh_ang=get_angel(mylatitude, mylongitude);
    set_angel=true;
}
else
{
    latLongString = "مکان شما یافت نشد دوباره امتحان کنید";
    Toast.makeText(this,latLongString, Toast.LENGTH_LONG).show();
}
}

1 个答案:

答案 0 :(得分:0)