2012-11-04 79 views
1

如何停止我的LocationListener中的onLocationChanged(),當我按下按鈕時,OnLocationChanged中的Toastbox不斷出現,即使離開應用程序也無法停止。如何停止我的LocationListener中的onLocationChanged()

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)  
      {   

      }  
     } 

回答

0

你可以應用此:

mlocManager.removeUpdates(mlocListener);

到一個按鈕或投放的onDestroy(),或在onPause()

編號:Android Activity

0

下面的代碼爲我工作:

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

只需撥打removeUpdates()方法,無論你想要停止更新!

相關問題