Arcgis Map : Get Current Location Error , Not displaying my current location - java

Hie,
I tried this sample code that one of the person who gave me this in my other question in stack overflow. I tried using this code but when i run the applicationn, it doesnt locate my current device and it doesnt even display a dot of my location .. The code does not give me any red underline errors but i am unable to locate the current location i am at.
What did i miss out? is there anyone who has a sample working source code file that i can download from to get my current device location??
the codes i used is as followed,
This is my MainActivity.class
public class MainActivity extends Activity {
MapView mMapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"));
mMapView = new MapView(this);
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location loc){
}
};
MyLocation mylocation = new MyLocation();
mylocation.getLocation(this, locationResult);
}
This is MyLocation.java
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}

You have to write the code for displaying a red dot in the gotLocation method which is currently empty. That is why you are not getting anything displayed on top of the map.

Related

How to keep LocationManager running in the background?

I am trying to write a tracing app, which needs to get location data and represent it on a map. The app works fine, when it is on screen, but when it if off-screen or the phone is locked, it will not receive and location updates. What can do I to keep it updating, even when the phone is locked?
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2500,5, locationListenerGPS);
...
LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(android.location.Location location) {
LatLongLastKnownPos = LatLongCurrentPos;
LatLongCurrentPos = new LatLng(location.getLatitude(), location.getLongitude());
if ( isMapReady ) { updateMap(); }
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};

Error when trying to start a Service in Android

I'm trying to write a service to locate the user by it's GPs location in Android. I wrotre a service for that. But alwasy when I try to start the service the error
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? appears. I already searched for this problem on google and added the follwoing line to my sourcecode:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
But the Error still appears. What can I do in order to make the service start without any errors? Here is my code:
MainActivity.java:
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
//GPs Standort bestimmung starten
Intent intent;
intent = new Intent(this, Gps_Service.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
initButtons();
}
}
"Gps_service.java":
public class Gps_Service extends Service implements LocationListener{
private double längengrad = 0.0, breitengrad = 0.0;
LocationManager locationManager;
Address adresse;
String straße, Ort, Land;
#Override
public void onCreate(){
super.onCreate();
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10000, 100, this);
}
#Override
public void onDestroy(){
super.onDestroy();
locationManager.removeUpdates(this);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onLocationChanged(Location location) {
längengrad = location.getLongitude();
breitengrad = location.getLatitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
Instead of running a service to retreive the user's location via GPS, use Google's Fused Location API.
The link provided has a detailed guide about how to implement it and is much more reliable and accurate in receiving location data.
Don't forget this gradle dependency as well:
compile 'com.google.android.gms:play-services-location:8.4.0'

Get GPS when Android Intent is Started

I thought this would be super easy - but this is taking waaaay longer than it should.
I'm simply trying to get the GPS coordinates to go to the logcat, that's literally it.
The intent fires fine. The "Intent Fired" message appears every time. The application just refuses to go to the location changed event.
If someone could take a look and let me know where I'm failing, it would be super appreciated.
public class MyReceiver extends IntentService implements LocationListener {
private LocationManager locationManager;
public MyReceiver() {
super("MyReceiver");
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe","Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe","Status");
}
}
Thank you
Well, the location manager works asynchronously, and IntentService is implemented in such a way, that when onHandleIntent(Intent intent) returns, the service stops itself. That means it's destroyed before any location can be provided to your onLocationChanged(location location) method. If you want to use IntentService you need to block the onHandleIntent(Intent intent) method from returning before you have your location, or use a standard Service and execute stopSelf when you obtain a Location object.
public class MyReceiver extends Service implements LocationListener {
private LocationManager locationManager;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_NOT_STICKY;
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
// this is where you stop the service
stopSelf();
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe", "Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe", "Status");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Keep in mind that this implementation won't run in a separate thread as default, as an IntentService would.

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

Categories

Resources