dimanche 28 décembre 2014

Execute location listener while switch button is active


I have a simple app containing a switch button (on/off) and a code which shows the current gps coordinates. I can't seems to combine those two. I want the locationmanager/listener will only operate while the switch is on 'on' mode. Any ideas ?


Thank you. here is the code :


public class GpsPage extends ActionBarActivity {



TextView tz;
TextView textLat;
TextView textLong;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_page);

tz = (TextView) findViewById(R.id.textviewtz);
Intent intent = getIntent();
String TeudatZeut = intent.getStringExtra("tz");
tz.setText("תעודת זהות " + TeudatZeut);

Switch onOffSwitch = (Switch) findViewById(R.id.switch1);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(getApplicationContext(), "It's on", Toast.LENGTH_SHORT).show();
}
});

textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class myLocationListener implements LocationListener {

@Override
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
double pAlt = location.getAltitude();
double pAcc = location.getAccuracy();
double pTime = location.getTime();
double pSpeed = location.getSpeed();
double pHeading =location.getBearing();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
}

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}








@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gps_page, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}


}





Aucun commentaire:

Enregistrer un commentaire