I'm beginner for android development.I use Gps service implementing LocationListener.I want to stop onLocationChanged() method using button click. I'm try to do this assigning null value to locationManager variable but it doesn't work it.
public class TabFragment1 extends Fragment implements LocationListener {
ImageButton btnRUN;
ImageButton btnSTOP;
private LocationManager locationManager;
Context ctx;
private double lat_new, lon_new = 0.0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ctx = container.getContext();
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
initializeApp(view);
return view;
}
private void initializeApp(View view) {
btnRUN = (ImageButton) view.findViewById(R.id.btnRun);
btnSTOP= (ImageButton) view.findViewById(R.id.btnStop);
btnRUN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runOnClick();
}
});
btnSTOP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopOnClick();
}
});
}
public void stopOnClick(){
locationManager =null;
}
public void runOnClick() {
locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, this);
}
@Override
public void onLocationChanged(Location location) {
lat_new=location.getLatitude();
lon_new=location.getLongitude();
String str="Lat :"+lat_new +"Lon :"+lon_new;
Toast.makeText(ctx,str,Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(ctx, "Gps turned on ", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(ctx, "Gps turned off ", Toast.LENGTH_LONG).show();
}
}
public void stopOnClick(){
locationManager.removeUpdates(this);
}
should work since your LocationListener is implemented by your Fragment
Note: Don't forget to also unregister the location listener in the onPause of your fragment to avoid crashes when the service tries to find TabFragment1 on an 'onLocationChanged' (imagine a user navigating on another fragment/activity of your app without pressing the 'stopOnClick' button):
@Override
public void onPause() {
locationManager.removeUpdates(this);
super.onPause();
}