android gps 定位2秒一次,GPS Android - 只定位一次

不要使用getLastKnownLocation,因为这可能会返回null或旧数据。

此代码仅在按下按钮时取出位置,而不是每次都取出。人们用来离开位置监听器在每个实例中监听并且杀死电池寿命所以使用我通过做大量研究发布的代码片段:

// get the text view and buttons from the xml layout

Button button = (Button) findViewById(R.id.btnGetLocation);

TextView latitude = (TextView) findViewById(R.id.textview4);

TextView longitude = (TextView) findViewById(R.id.textview5);

final LocationListener locationListener = new LocationListener() {

@Override

public void onLocationChanged(Location location) {

mlocation = location;

Log.d("Location Changes", location.toString());

latitude.setText(String.valueOf(location.getLatitude()));

longitude.setText(String.valueOf(location.getLongitude()));

}

@Override

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

Log.d("Status Changed", String.valueOf(status));

}

@Override

public void onProviderEnabled(String provider) {

Log.d("Provider Enabled", provider);

}

@Override

public void onProviderDisabled(String provider) {

Log.d("Provider Disabled", provider);

}

};

// Now first make a criteria with your requirements

// this is done to save the battery life of the device

// there are various other other criteria you can search for..

criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_COARSE);

criteria.setPowerRequirement(Criteria.POWER_LOW);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setSpeedRequired(false);

criteria.setCostAllowed(true);

criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);

criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

// Now create a location manager

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

// This is the Best And IMPORTANT part

Looper looper = null;

// Now whenever the button is clicked fetch the location one time

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

locationManager.requestSingleUpdate(criteria, locationListener, looper);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值