1

如何在我的 LocationListener 中停止 onLocationChanged(),当我按下按钮时,onLocationChanged 中的 Toastbox 不断出现,即使我离开应用程序也无法停止。

Button btn_location =(Button) findViewById(R.id.button4);
btn_location.setOnClickListener(new OnClickListener() {
public void onClick(View v) { 


               LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
               LocationListener mlocListener = new MyLocationListener(); 
               mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 
        }

    });

 public class MyLocationListener implements LocationListener     {  


            public void onLocationChanged(Location loc)       
            {   

                loc.getLatitude();         
                loc.getLongitude();          
                String Text = "My current location is: " +         "Latitud = " + loc.getLatitude() +         "Longitud = " + loc.getLongitude();          
                Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();       
             }        
            public void onProviderDisabled(String provider)       
            {         
                Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();       
             }        
            public void onProviderEnabled(String provider)       
            {         
                Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();       
             }        
            public void onStatusChanged(String provider, int status, Bundle extras)       
            {        

            }     
         } 
4

2 回答 2

0

你可以应用这个:

mlocManager.removeUpdates(mlocListener);

到按钮或放入 onDestroy() 或 onPause()

参考:Android 活动

于 2012-11-22T18:53:23.330 回答
0

以下代码对我有用:

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    aLocationManager.removeUpdates(aLocationListener);
}

只需在要停止更新的任何地方调用 removeUpdates() 方法!

于 2014-04-18T14:22:51.403 回答