Android locationManager请求LocationUpdate不';行不通

Android locationManager请求LocationUpdate不';行不通,android,Android,我正在开发一个应用程序,其中列出了最接近用户的餐厅。单击“刷新”按钮时,它会列出用户当前位置的餐厅。我正在使用位置管理器,仅当活动进入前台时才请求更新(onResume),以避免电池的持续使用。当应用程序进入onPause()时,位置更新将停止。当我通过终端传递更新时,它可以在模拟器上正常工作 问题: 当我实际更改位置(比如开车5英里)并打开应用程序和活动以显示最近的餐厅时,需要很长时间(4-5分钟)才能刷新位置,直到应用程序继续显示前一位置的餐厅。但是,如果我实际改变了我的位置,访问谷歌地图,

我正在开发一个应用程序,其中列出了最接近用户的餐厅。单击“刷新”按钮时,它会列出用户当前位置的餐厅。我正在使用位置管理器,仅当活动进入前台时才请求更新(onResume),以避免电池的持续使用。当应用程序进入onPause()时,位置更新将停止。当我通过终端传递更新时,它可以在模拟器上正常工作

问题: 当我实际更改位置(比如开车5英里)并打开应用程序和活动以显示最近的餐厅时,需要很长时间(4-5分钟)才能刷新位置,直到应用程序继续显示前一位置的餐厅。但是,如果我实际改变了我的位置,访问谷歌地图,然后打开我的餐馆应用程序,那么它会立即工作。我已确保GPS已打开。在我打开活动后,如何让位置经理立即启动并刷新位置? 提前谢谢你

package com.mortley.android.restaurantsaver;

public class NearbyRestaurantActivity extends ListActivity implements OnClickListener, LocationListener{
    private Button refreshButton, searchRestaurants; 
    ImageButton goToSearch;
    private double[] lastKnownLocation;
    private EditText locationEditText;
    private LocationManager locManager;
    private LocationListener locListener;
    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearbyrestaurants);
        refreshButton = (Button)findViewById(R.id.reloadButton);
        refreshButton.setOnClickListener(this);

        searchRestaurants = (Button)findViewById(R.id.searchButton);
        searchRestaurants.setOnClickListener(this);
        goToSearch = (ImageButton)findViewById(R.id.goLocationButton);
        goToSearch.setOnClickListener(this);
        locationEditText = (EditText)findViewById(R.id.addressTextBox);
        locationEditText.setVisibility(View.GONE);
        goToSearch.setVisibility(View.GONE);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);//??


        locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 100, this);

        //checks network connectivity
        boolean checkConnection = isNetworkAvailable();
        if(!checkConnection){
            Toast.makeText(getApplicationContext(), "Check your Network Connectivity", Toast.LENGTH_LONG).show();
        }

        if(checkConnection){
            //sets current location parameters for the user
            lastKnownLocation = RestaurantHelper.getLastKnownLocation(this);
            //Log.v("NearbyRestaurantActivity", "This"+this);

            RestaurantApplication application = (RestaurantApplication) this.getApplication();
            RestaurantAdapter restaurantAdapter = new RestaurantAdapter(this, R.layout.restaurantrow,  R.id.label,new ArrayList<RestaurantReference>());
            restaurantAdapter.setLastKnownLocation(lastKnownLocation);  


            //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
            application.setRestaurantAdapter(restaurantAdapter);
            //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
            setListAdapter(restaurantAdapter);
            //Make a webservice call in a different thread passing Keyword for URL as a string array.
            RestaurantHttpAsyncTask m_progressTask;
            String[] keywords = {"", "american", "asian", "italian","mexican"};
            //String[] keywords = {"indian"};
            m_progressTask = new RestaurantHttpAsyncTask(NearbyRestaurantActivity.this, keywords);
            m_progressTask.setRestaurantAdapter(restaurantAdapter);
            m_progressTask.execute();
        }
    }

    @Override
    public void onClick(View v) {   
        //Refresh button helps to refresh the restaurant list on location change. Again it makes a call to the webservice using Async Task
        if(v.getId() == refreshButton.getId() ){


            try {
                gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            // don't start listeners if no provider is enabled
            if (!gps_enabled && !network_enabled) {
                Toast.makeText(getApplicationContext(), "Sorry, Location is not determined. Please enable your Network Providers.", Toast.LENGTH_LONG).show();


            }

            //check network connectivity before refresh
            boolean checkConnection = isNetworkAvailable();
            if(!checkConnection){
                Toast.makeText(getApplicationContext(), "Check your Network Connectivity", Toast.LENGTH_LONG).show();
            }
            if(checkConnection){

                RestaurantApplication application = (RestaurantApplication) this.getApplication();
                RestaurantAdapter restaurantAdapter = new RestaurantAdapter(this, R.layout.restaurantrow,  R.id.label, new ArrayList<RestaurantReference>());
                restaurantAdapter.setLastKnownLocation(lastKnownLocation);  
                //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
                application.setRestaurantAdapter(restaurantAdapter);
                //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
                setListAdapter(restaurantAdapter);
                //Make a webservice call in a different thread passing Keyword for URL as a string array.
                RestaurantHttpAsyncTask m_progressTask, m_progressTask1;
                String[] keywords = {"", "american", "asian", "italian","mexican", "chinese", "indian"};
                //String[] keywords = {"Chinese"};
                m_progressTask = new RestaurantHttpAsyncTask(NearbyRestaurantActivity.this, keywords);
                m_progressTask.setRestaurantAdapter(restaurantAdapter);
                m_progressTask.execute();
            }
        }

        if(v.getId() == goToSearch.getId() ){

            Activity child = this;
            while(child.getParent() != null){
                child = child.getParent();
            }
            TabGroup1Activity parent = (TabGroup1Activity)getParent();


            InputMethodManager imm = (InputMethodManager)getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(locationEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            //changes ** restaurantAdapter to RestaurantAdapter1 to test & application to application1  
            RestaurantApplication application1 = (RestaurantApplication) this.getApplication();
            RestaurantAdapter restaurantAdapter1 = new RestaurantAdapter(this, R.layout.restaurantrow,  R.id.label, new ArrayList<RestaurantReference>());
            restaurantAdapter1.setLastKnownLocation(lastKnownLocation);  
            //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
            application1.setRestaurantAdapter(restaurantAdapter1);
            //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
            setListAdapter(restaurantAdapter1);
            //Make a webservice call in a different thread passing Keyword for URL as a string array.
            RestaurantHttpAsyncTaskTextSearch m_progressTask, m_progressTask1;
            String keywords = locationEditText.getText().toString();
            if(keywords.equals("")){
                keywords = "Pizza in Palo Alto";
            }
            keywords = keywords.replaceAll(" ", "%20");
            keywords = keywords.replaceAll(",", "%20");
            m_progressTask = new RestaurantHttpAsyncTaskTextSearch (NearbyRestaurantActivity.this, keywords);
            m_progressTask.setRestaurantAdapter(restaurantAdapter1);
            m_progressTask.execute();

            locationEditText.setVisibility(View.GONE);
            goToSearch.setVisibility(View.GONE);
        }
        if(v.getId() == searchRestaurants.getId() ){
            if(goToSearch.isShown() == true){
                goToSearch.setVisibility(View.GONE);
                locationEditText.setVisibility(View.GONE);
            }
            else if(goToSearch.isShown() == false){
                //check network connectivity before refresh
                boolean checkConnection = isNetworkAvailable();
                if(!checkConnection){
                    Toast.makeText(getApplicationContext(), "Check your Network Connectivity", Toast.LENGTH_LONG).show();
                }
                if(checkConnection){
                    goToSearch.setVisibility(View.VISIBLE);
                    locationEditText.setVisibility(View.VISIBLE);

                }
            }
        }

    }
    //Method to check network connectivity
    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
        = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
            //Log.d("network", "Network available:true");
            return true;
        } else {
            //Log.d("network", "Network available:false");
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50, 100, this); 
        //Log.v("NearbyRestaurantActivity", "In OnResume()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        locManager.removeUpdates(this); 
        //Log.v("NearbyRestaurantActivity", "In onPause()");

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

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

    }
}






public class RestaurantHelper {

public static double[] getLastKnownLocation(Activity activity){
    double lat = 0.0;
    double lon = 0.0;
    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);    
    Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  

    if(location == null){
        lat = 0.0;
        lon = 0.0;
    }
    else{
        //Log.v("Latitude", Double.toString(location.getLatitude()));
        //Log.v("Longitude", Double.toString(location.getLongitude()));

        lat = location.getLatitude();
        lon = location.getLongitude();
    }
    return new double[]{lat,lon};
}
}
package com.mortley.android.restaurantsaver;
公共类NearbyRestaurantActivity扩展ListActivity实现OnClickListener、LocationListener{
私人按钮刷新按钮,搜索餐厅;
图像按钮搜索;
私人双[]位置;
私有EditText位置EditText;
私人场所经理;
私有位置侦听器;
专用布尔值gps_enabled=false;
专用布尔网络_enabled=false;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.nearbyrestaurants);
refreshButton=(按钮)findViewById(R.id.reloadButton);
refreshButton.setOnClickListener(此);
searchRestaurants=(按钮)findViewById(R.id.searchButton);
searchRestaurants.setOnClickListener(this);
goToSearch=(ImageButton)findViewById(R.id.goLocationButton);
setOnClickListener(这个);
locationEditText=(EditText)findViewById(R.id.addressTextBox);
locationEditText.setVisibility(View.GONE);
goToSearch.setVisibility(View.GONE);
locManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);/??
locManager.requestLocationUpdates(LocationManager.GPS_提供程序,1000100,此);
//检查网络连接
布尔checkConnection=isNetworkAvailable();
如果(!检查连接){
Toast.makeText(getApplicationContext(),“检查网络连接”,Toast.LENGTH_LONG.show();
}
如果(检查连接){
//为用户设置当前位置参数
lastKnownLocation=RestaurantHelper.getLastKnownLocation(此);
//Log.v(“近距离稳定活动”、“此”+此);
RestaurantApplication application=(RestaurantApplication)this.getApplication();
RestaurantAdapter RestaurantAdapter=new RestaurantAdapter(this,R.layout.restaurantrow,R.id.label,new ArrayList());
restaurantapter.setLastKnownLocation(lastKnownLocation);
//在RestaurantApplication类中为RestaurantAdapter设置全局变量。
应用程序。setRestaurantAdapter(restaurantAdapter);
//首先设置适配器,然后在RestaurantTPasynctask进行web服务调用时更新它。
setListAdapter(餐厅适配器);
//在不同的线程中进行webservice调用,将URL的关键字作为字符串数组传递。
Restauranttpasynctask m_progressTask;
字符串[]关键字={“,”美国“,”亚洲“,”意大利“,”墨西哥“};
//字符串[]关键字={“印度”};
m_progressTask=新餐厅TTPasynctask(NearbyRestaurantActivity.this,关键字);
m_progressTask.setRestaurantAdapter(restaurantAdapter);
m_progressTask.execute();
}
}
@凌驾
公共void onClick(视图v){
//“刷新”按钮有助于在位置更改时刷新餐厅列表。它再次使用异步任务调用Web服务
if(v.getId()==refreshButton.getId()){
试一试{
gps_enabled=LocationManager.isProviderEnabled(LocationManager.gps_提供程序);
}捕获(例外情况除外){
例如printStackTrace();
}
试一试{
network_enabled=LocationManager.isProviderEnabled(LocationManager.network_提供程序);
}捕获(例外情况除外){
例如printStackTrace();
}
//如果未启用任何提供程序,则不要启动侦听器
如果(!gps_已启用&&!网络_已启用){
Toast.makeText(getApplicationContext(),“抱歉,位置未确定。请启用网络提供商。”,Toast.LENGTH_LONG).show();
}
//刷新前检查网络连接
布尔checkConnection=isNetworkAvailable();
如果(!检查连接){
Toast.makeText(getApplicationContext(),“检查网络连接”,Toast.LENGTH_LONG.show();
}
如果(检查连接){
RestaurantApplication application=(RestaurantApplication)this.getApplication();
RestaurantAdapter RestaurantAdapter=new RestaurantAdapter(this,R.layout.restaurantrow,R.id.label,new ArrayList());
restaurantapter.setLastKnownLocation(lastKnownLocation);
//在RestaurantApplication类中为RestaurantAdapter设置全局变量。
应用程序。setRestaurantAdapter(restaurantAdapter);
//首先设置适配器,然后在RestaurantTPasynctask进行web服务调用时更新它。
setListAdapter(餐厅适配器);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
 HomeScreen.getLocationManager().requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(final Location location) {
        }
    });
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100, this)
locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 100, this)