Get MyLocation using GPS - how to implement 'if else' statement? - java

I am new to android, and reverse-engineering my way into learning java.
Having got as far using the code below, i have a few problems needing to be resolved while customising it to suit my inentions.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
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();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
The problem is my (android) home screen starts with a checkboxed page showing two choices (checboxes);
GPS On (Enabled)
GPS Off (Disabled)
Now, question is, i have no idea how to write the 'if else' statement/method which could which could help direct the 'On' scenario to the next stage of getting my location, and for directing the 'Off' scenario back to beginning (Home screen).
Where/how in the code do i declare/insert the checkbox code?
Any assistance welcome please.
Thanks

Basic checkbox check:
final CheckBox cbGPS = (CheckBox) findViewById(R.id.checkBox1);
cbGPS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
// do this if checked
StartGPSMethod();
} else {
// if not checked do this
// do nothing or
EndGPSMethod();
}
}
});

Related

setText in app when GPS enabled/disabled in device

I'm using the following code to change two text views based on when the user turns on/off their network and their GPS. I was able to get the network text view to work but not the location text view. I think I am using the wrong filter, but I don't know which to use instead. Any suggestions/answers?
public class MainActivity extends AppCompatActivity {
TextView networkTextView;
TextView locationTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkTextView = findViewById(R.id.networkTextView);
locationTextView = findViewById(R.id.locationTextView);
IntentFilter filter1 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver1, filter1);
IntentFilter filter2 = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
registerReceiver(broadcastReceiver2, filter2);
}
BroadcastReceiver broadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noNetworkConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noNetworkConnectivity) {
networkTextView.setText("Disconnected");
} else {
networkTextView.setText("Connected");
}
}
}
};
BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION, false);
if (noLocationConnectivity) {
locationTextView.setText("Disconnected");
} else {
locationTextView.setText("Connected");
}
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver1);
unregisterReceiver(broadcastReceiver2);
}
}
Update:
In the broadcast receiver for the location I replaced
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION, false);
with
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean locationConnectivity = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
but that didn't work. Maybe need to request location data permission from user?
Update 2:
Realized that it is registering boolean changes of the LocationManager.GPS_provider, but not initially. Only after the Location setting is manually changed after the app is started does the text change, unlike with the network check that changes the text as soon as the app starts.
I think that this question has already been answered here
But I'm thinking if use LocationManager and LocationListener is a good idea or not, I mean, LocationListener has those overrided methods:
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
I leave it to your consideration

isProviderEnabled() never getting called android

I am writting code for getting current location (latitude and longitude) of my phone. I display a toast whether Network Location service is provided by the phone or not. This toast doesn't show up ever. The other question is, for getting current location using Network_location, will the app use phone's gprs/internet or not?
I have created the instance of this class in the main activity and then get data using Latitude and Longitude variables of this class, in another class which extends broadcast reciever .
public class GpsClass extends Activity{
public static String Latitude="";
public static String Longitude="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() { // anonymous class
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location currentLocation) {
double lat= currentLocation.getLatitude();
Latitude = Double.toString(lat);
double longt= currentLocation.getLongitude();
Longitude = Double.toString(longt);
}
};
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
Toast.makeText(getApplicationContext(), "Network enabled", 0).show();
}
else
Toast.makeText(getApplicationContext(), "Network not enabled", 0).show();
}
}
Is there anything I am doing wrong?
Regards
I think the problem is that you are passing 0 for duration i.e. last parameter of makeText() method.
Try passing Toast.LENGTH_SHORT or Toast.LENGTH_LONG.
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
Toast.makeText(getApplicationContext(), "Network enabled", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Network not enabled", Toast.LENGTH_LONG).show();
This can help you to get answer to your first question.
The answer to your second question is - No, the app will not use phone's gprs/internet for getting location through network provider.
The problem is setting 0 for duration.
This is a sample example:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude());
// Set Toast Here To Diplay location
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//10000 means request update every 10 sec
//10 tell listener that if location change more than 10m then run locationChanged method
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, locationListener);
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, locationListener);
}

GPS Android - get positioning only once

Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?
In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.
Dont use the getLastKnownLocation because that could be returning null or old data.
This code Only fetches the location once a button is pressed and not every time. People use to leave the location listener listen in every instance and that kills the battery life so Use the code snippet I have posted by doing lots of research:
// get the text view and buttons from the xml layout
Button button = (Button) findViewById(R.id.btnGetLocation);
final TextView latitude = (TextView) findViewById(R.id.textview4);
final TextView longitude = (TextView) findViewById(R.id.textview5);
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.d("Location Changes", location.toString());
latitude.setText(String.valueOf(location.getLatitude()));
longitude.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Status Changed", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Provider Enabled", provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Provider Disabled", provider);
}
};
// Now first make a criteria with your requirements
// this is done to save the battery life of the device
// there are various other other criteria you can search for..
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
// Now create a location manager
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// This is the Best And IMPORTANT part
final Looper looper = null;
// Now whenever the button is clicked fetch the location one time
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, locationListener, looper);
}
});
First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.
Addition
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}

Google maps api not placing marker at fine location

My code is supposed to find out the users location and place a marker on the map upon entering the application. My location value always equals null, and never receives a value.
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "AYO",
"Whats good yo");
CustomPinpoint custom = new CustomPinpoint(d, CampusMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
} else {
Toast.makeText(CampusMap.this, "Couldn't get provider",
Toast.LENGTH_SHORT).show();
}
}
I've had a relatively similar issue with a GPS RPG I was working on and here are some things I noticed:
Firstly, it can take a while for your location to initially be found, which would cause that issue since you're only checking if the location is null.
You may also want to make sure the device's location services are actually enabled before doing anything:
private boolean doLocationsCheck(){
if(!checkLocationEnabled()){
final CharSequence[] items = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Location must be enabled to play this game! Would you like to enable it now?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final int i = item;
runOnUiThread(new Runnable() {
public void run() {
if(i == 0){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
quit();
}
else{
quit();
}
}
});
}
}).show();
AlertDialog alert = builder.create();
return false;
}
else {
return true;
}
}
private boolean checkLocationEnabled(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER) || service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return enabled;
}
After I've made sure the providers are available I setup a connection like so:
private void setupLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
runOnUiThread(new Runnable() {
public void run() {
mLocation = location;
//Log.d(TAG, "Latitude: " + location.getLatitude() + " - Longitude: " + location.getLongitude());
saveLocation();
}
});
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Can set to GPS or network, whichever is available
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The location is then set in a global variable whenever it's updated, and then saved to the preferences. This way, in the event that the providers are enabled, but are taking a while to retrieve the location, the user can still continue to use the application with their last known location that the app stored (does not apply to the first time the program is run).
I know I left out a lot there, but I figured it wasn't really necessary since it was either self-explanatory or already explained in a previous answer.
Cheers~
/*
* getting the best location using the location manager
* Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1000 Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1
*/
LocationManager mLocation;
private String mBestProvider;
// in your onCreate() do the following
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
// and use the following locationListener inner class
private class LocationListenerManager implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MapViewActivity.this, message, Toast.LENGTH_LONG).show();
Log.v("poiint=====", ""+message);
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapViewActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
You have to initialize the locationlistener in the onstartActivity before on create so that it location obtain the location value before onCreate.

Can't get location on application startup

I am trying to develop little application which at startup shows the name of current location in a toast or something. The code I wrote will show a Toast on the display with the location only is I send the coordinates manually from the Emulator Control View from Eclipse.
My question: Is there a way to force somehow this sending of coordinates at the startup, because I want that Toast when the application is loaded? And how can I do it? Thanks.
Here is the code:
public class HomeActivity extends Activity implements LocationListener {
private LocationManager locationManager;
private String welcomeMsg;
private String crtLocationName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initLocationManager();
}
private void initLocationManager(){
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5000, this);
}
*/
#Override
public void onLocationChanged(Location location) {
if (location != null) {
try {
crtLocationName = getLocationName(location);
Toast.makeText( getApplicationContext(), crtLocationName, Toast.LENGTH_LONG).show();
} catch (IOException e) {
welcomeMsg = "Location cannot be determined";
crtLocationName = "";
}
// locationManager.removeUpdates(this);
}
}
#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
}
}
As Emulator doesn't have a GPS receiver, the method onLocationChanged will be only invoked when you give some new coordinates through DDMS.
On the real phone, it will not show a Toast instantly; it will wait before it locates the GPS satellite and receive a GPS fix, then it will show the Toast message.

Categories

Resources