Waiting for GPS location before proceeding Android - java

I am aware there are a number of similar questions floating around but could not find a suitable answer in my searches.
My App has an activity which relies on the GPS location to function. The app will crash if it is run immediately after start up due to null pointer exceptions etc where the location is null. I am aware these are my programming errors and I should handle the exceptions, but the activity is still useless until a GPS fix is found.
When the app crashes I get the "Searching for GPS" icon, and if this is left for long enough a GPS location is found and the app can be run with no issue.
I have created another activity to act as a home screen which will enable the button to link to the above activity when a GPS location is found. The problem is that it doesn't seem to find or be looking for a GPS signal. By this i mean that no "Searching for GPS" icon appears and the button is never enabled. The code for this home activity is below, have I missed something?
My activity implements LocationListener, and the code below is in the Activity "onCreate" method. "startExplore" starts my GPS reliant activity.
exploreButton = (Button) findViewById(R.id.button1);
exploreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startExplore();
}
});
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
exploreButton.setEnabled(false);
exploreButton.setText("Finding location . . .");
}
This is my "onLocationChanged" method. As i said above, unlike my other activity I do not get the "Searching for GPS" icon and the location does not appear to be found despite this being the same method used in my other Activity. So is this the correct technique for waiting until a location is found, and can anyone identify any mistakes?
public void onLocationChanged(Location location) {
exploreButton.setEnabled(true);
exploreButton.setText("Found signal");
}

Call the
locationManager.requestLocationUpdates(locationProvider, 0, 0, this)
to get the updated location.. It might be the source of the problem.. Because of this only "Searching for GPS" wasn't initiated I think..

Move it out the onCreate methode or put it in a handler or so.
Example:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//methods you want.
}
}, 100);

Related

Android refresh google map after turning on location

I have a google map in my project. First of all, I check whether the user has location enabled. If the user does not have location enabled, a dialog box pops up asking them to enable location. When the user accepts this prompt, he or she is redirected to the settings page where they can enable location.
The problem is after enabling location and press back, the map remains in its previous state, i.e. does not zoom to the user's current location.
How can I solve this?
I think you should reload the map on the method onResume:
edit (i am assuming that you have declared the mGoogleMap object on class scope):
GoogleMap googleMap;
#Override
public void onResume() {
super.onResume();
if(googleMap != null){
googleMap.clear();
// add the markers just like how you did the first time
}
}
You have to implement LocationListener
public class FragmentMap extends SupportMapFragment implements LocationListener
{
GoogleMap mGoogleMap_;
[...]
#Override
public void onLocationChanged(Location location)
{ CameraPosition.Builder builder = CameraPosition.builder(mGoogleMap_.getCameraPosition());
builder.target(new LatLng(location.getLatitude(), location.getLongitude()));
mGoogleMap_.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build())); // CameraUpdateFactory.newLatLngZoom(...) if you need to zoom too
}
[...]

Threading and Progressbar in Android?

Hey guys so I'm trying to display gps distance between the user and some place on a card they can see. The problem is, I think the main thread splits or does 2 things at once. At the code below, Android makes a toast while doing the code in the if(flag) statement... so it toasts the GPS difference without getting the coordinates of the user...How do i make it so that, it does if(flag) statement first then goes on to do the toast after and outside the if statement?
#Override
public void onResume()
{
super.onResume();
ImagePath = getIntent().getStringExtra("imagePath");
if(ImagePath == null)
{
Toast.makeText(this,"hello everyone",Toast.LENGTH_LONG).show();
}
if(newCardAdded)
{
flag = displayGpsStatus();
if(flag)
{
editLocation.setText("Please!! move your device to" +
" see the changes in coordinates." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();//LocationListener actually physically gets your location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
else
{
alertbox("Gps Status!!", "Your GPS is: OFF");
}
Global_Class.getInstance().getValue().getlatitude = place_lat;
Global_Class.getInstance().getValue().getlongitutde = place_lon;
String gps_distance = String.valueOf(gps_difference(user_lon, user_lat,place_lon,place_lat));
Toast.makeText(this, gps_distance, Toast.LENGTH_LONG).show();
}
}
LocationManager#requestLocationUpdates
Your locationListener must implement onLocationChanged(Location) method, which will be called for each location update. Then calculate distance and make a toast in that method. Because requestLocationUpdates(...) runs in another thread, there's no way to confirm that it is done before Toast.makeText(...), so you must use your MyLocationListener.

Location updates not showing for GPS

I'm trying to retrieve the device's current location using the device's GPS. When I register for updates (as shown below) for LocationManager.GPS_PROVIDER no updates are rolling, yet when I do the same for LocationManager.NETWORK_PROVIDER I get the updates.
I have tested it on my Android device (not the emulator). I have also made sure the GPS is on. Other apps (not mine) are able to access my location. What am I missing here?
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationRetrieved(location, this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { providerDisabled(); }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
GPS start up is not an instant process. The receiver basically has to know the position of each of the GPS satellites in the constellation in order to calculate it's location
Are you first checking if there is a last known location which you can use? Most apps first check for it and then search for a location.
You should check wheter your phone is allowing the gathering of location with GPS.
Probabily what is happening is that in Settings -> Location you only have the checkbox for wireless location. If so, the GPS_PROVIDER doesn't work.

Android: quick search to map results

Does anyone know how to activate a map from a quick search box?
My app displays the users location and some places pulled from my website. I have added a quick search box, following instruction from Google Android docs but I can't get it to initiate the map. I can get it to print the query, so I know its getting the data, but when I try to sumbit the query to a class, or set the content view it crashes! (I have commented out the lines that cause a crash).
public class SearchActivity extends MapActivity {
public boolean touched = false;
private MapView mapView;
Main mc = new Main();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//mapView = (MapView) findViewById(R.id.mapView);
//mapView.getController();
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
//mc.activateMapFromQuery(query);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
here is what I can read in the LogCat which I believe may be relevant:
Starting Activity: Intent { act=android.intent.action.SEARCH flg=0x10000000 cmp=com.maps.android.example/com.maps.android.example.Main paused=false}
onSignalStrengthChanged
onSignalStrengthChanged
grantUriPermission URI=file:///data/local/tmp/Example.apk
No content provider found for:
Force stopping package com.maps.android.example uid=10115
WIN DEATH: Window{40834690 com.maps.android.example/com.maps.android.example.Main paused=false}
I found the solution!
In the CatLog above it says onSignalStrengthChanged after the Starting Activity. This made me realise that GPS was still updating the user location when it was trying to perform the search and display the new map. So I simply turned off the GPS activity on the initiation of the intent.
This actually sped up the app, and now the search works!
Thanks to everyone who looked at this and tried to help. Hope this is of some assistance to others :)

Location not being updated on new geo fix in android emulator

I am trying to make it so a MapView zooms to a current location based on a GeoPoint. I am setting the location using the geo fix command in telnet. My problem is that when I first input a location using geo fix my code will correctly navigate to a location on the map. If I try to set another location using geo fix however it does not update. Here is the code to update:
public void updateLocation(Location loc) {
p = new GeoPoint((int)(loc.getLongitude() * 1E6),(int)(loc.getLatitude() * 1E6));
mc = mapView.getController();
mc.animateTo(p);
}
and here is my code to call the update:
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
etc...
I have the following in onResume():
super.onResume();
myLocationManager.requestLocationUpdates("gps", 0, 200, onLocationChange);
The points I am trying to geo fix to are far enough apart to meet the minimum distance requirement. Anyone have any ideas of what I'm missing?
Call mapView.invalidate(); (see View:invalidate()) or mapView.postInvalidate(); (see View:postInvalidate()), depending on if it runs on UI thread or not, after
mc.animateTo(p);
Assuming your MapActivity implements LocationListener, then change
myLocationManager.requestLocationUpdates("gps", 0, 200, onLocationChange);
to
myLocationManager.requestLocationUpdates("gps", 0, 200, this);
'this' holds the location listener

Categories

Resources