如何更好地处理GPS位置和android [英] How to better handle GPS location and android

查看:247
本文介绍了如何更好地处理GPS位置和android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有listview的片段,它检索用户位置,然后根据用户位置更新列表视图。

我的代码存在的问题是,它似乎抓住位置更新列表,然后继续更新。重新加载列表,几乎到了烦人的地步。这里是我的代码:

  public class FindBrewery extends Fragment implements LocationListener {

private TextView latituteField;
私人TextView longitudeField;
LocationManager locationManager;
私有字符串提供程序;


@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Context c = getActivity()。getApplicationContext();
locationManager =(LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);




$ b public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);



查看onCreateView(LayoutInflater inflater,ViewGroup容器,
Bundled savedInstanceState){
//待办事项更改视图
查看rootView = inflater.inflate(R.layout.beer_location_list,container,false);

//获取位置管理器
//定义条件如何选择位置提供者 - >使用
//默认
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
位置位置= locationManager.getLastKnownLocation(provider);

//初始化位置字段
if(location!= null){
System.out.println(Provider+ provider +has been selected。);
onLocationChanged(location);
} else {

}


return rootView;




$ b / *启动时请求更新* /
@Override
public void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider,400,1,this);

$ b $ *当Activity暂停时移除位置监听器更新* /
@Override
public void onPause(){
super.onPause() ;
locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location){
int lat =(int)(location.getLatitude());
int lng =(int)(location.getLongitude());
//latituteField.setText(String.valueOf(lat));
//longitudeField.setText(String.valueOf(lng));

//Toast.makeText(this,Finding your loaction,Toast.LENGTH_SHORT).show();

//为位置
调用asycn任务String url =myURL;

Log.d(urlTest,url);

//异步任务在这里
new GetNearbyBreweries(this.getActivity())。execute(url);




$ b $覆盖
public void onStatusChanged(String provider,int status,Bundle extras){
/ / TODO自动生成的方法存根


$ b @Override
public void onProviderEnabled(String provider){
//Toast.makeText(this, Enabled new provider+ provider,Toast.LENGTH_SHORT).show();


$ b $ @覆盖
public void onProviderDisabled(String provider){
//Toast.makeText(this,Disabled provider+ provider, Toast.LENGTH_SHORT).show();
}



}


解决方案

也许你会想尝试这种方法:

  LocationClient mLocationClient; 
LocationRequest mLocationRequest;
$ b @Override
public void onAttach(Activity activity){
if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity)){
mLocationClient = new LocationClient(activity,activity,activity );

mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5000);
mLocationRequest.setNumUpdates(1);
mLocationRequest.setFastestInterval(1000);


$ b @Override
public void onActivityCreated(Bundle savedInstanceState){
if(mLocationClient!= null){
mLocationClient。连接(); (mLocationClient!= null){
if(mLocationClient。


@Override
protected void onStop(){
isConnected()){
mLocationClient.removeLocationUpdates(this);
}

mLocationClient.disconnect();
}
super.onStop();

$ b @Override
public void onConnected(Bundle dataBundle){
LocationManager lm =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
mLocationClient.requestLocationUpdates(mLocationRequest,this);
}

@Override
public void onLocationChanged(Location location){
int lat =(int)(location.getLatitude());
int lng =(int)(location.getLongitude());

//发布到更新列表项的处理程序
}



诀窍在于:




  • 您不使用 getLastKnownLocation 因为它使用缓存,而且通常会返回错误的数据,所以你设置 setNumUpdates(1),所以你 don 't 需要调用 removeLocationUpdates()



< t忘记AndroidManifest权限:

 < uses-permission android:name =android.permission.ACCESS_COARSE_LOCATION/> 
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>


I have a fragment with a listview in it, that retrieves the users location, then updates the list view based on the users location.

The problem with my code, is that it seems to grab the location update the list, then keep updating. And reloading the list, almost to the point of annoyance. Here is my code:

public class FindBrewery extends Fragment implements LocationListener {

    private TextView latituteField;
    private TextView longitudeField;
    LocationManager locationManager;
    private String provider;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Context c = getActivity().getApplicationContext();
        locationManager =(LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);

    }



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //todo change view
        View rootView = inflater.inflate(R.layout.beer_location_list,container, false);

        // Get the location manager
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {

        }


        return rootView;
    }




    /* Request updates at startup */
    @Override
    public void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    public void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        //latituteField.setText(String.valueOf(lat));
        //longitudeField.setText(String.valueOf(lng));

        //Toast.makeText(this, "Finding your loaction",Toast.LENGTH_SHORT).show();

        //call asycn task for location
        String url = "myURL";

        Log.d("urlTest", url);

        //async task goes here
        new GetNearbyBreweries(this.getActivity()).execute(url);



    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        //Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        //Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
    }



}

解决方案

Maybe you'd want to try this approach:

LocationClient mLocationClient;
LocationRequest mLocationRequest;

@Override
public void onAttach(Activity activity) {
  if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity)) {
    mLocationClient = new LocationClient(activity, activity, activity);

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(5000);
    mLocationRequest.setNumUpdates(1);
    mLocationRequest.setFastestInterval(1000);
  }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
  if (mLocationClient != null) {
    mLocationClient.connect();
  }
}

@Override
protected void onStop() {
  if (mLocationClient != null) {
    if (mLocationClient.isConnected()) {
      mLocationClient.removeLocationUpdates(this);
    }

    mLocationClient.disconnect();
  }
  super.onStop();
}

@Override
public void onConnected(Bundle dataBundle) {
  LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  mLocationClient.requestLocationUpdates(mLocationRequest, this);
}

@Override
public void onLocationChanged(Location location) {
  int lat = (int) (location.getLatitude());
  int lng = (int) (location.getLongitude());

  // post to a handler to update the list items
}

The trick is in the following:

  • you don't use getLastKnownLocation as it uses cache and more often than not returns wrong data,
  • you set setNumUpdates(1) so you don't need to call removeLocationUpdates()

Don't forget AndroidManifest permissions:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

这篇关于如何更好地处理GPS位置和android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆