Android development - GPS not working - Application hangs when co-ordinates sent - android-emulator

Problem Background:
I am somewhat new to Android development. All I'm trying to do, for now, is to get GPS coordinates from the GPS device of the phone and display them on Google Maps or just in a TextView, or whatever. The main task is to get them.
I've read a number of tutorials. I'm using
- Android 2.3.3
- API level 10
- Eclipse 3.6.1
- Windows 7
Problem Description :
I have written a class GeoUpdateHandler which implements LocationListener and implements its methods onLocationChange() etc. And in MyMapsActivity, I use the regular requestLocationUpdates of the LocationManager to get periodic updates.
When I run the application, I send GPS coordinates from the Emulator Control of Eclipse (Window --> Show View --> Other --> Android --> Emulator Control) to send Longitude and Latitude. As soon as the emulated device gets the coordinates, the application hangs. Nothing happens and the cursor changes to the blue circle (which signifies thinking/stuck) and nothing happens. If I use locationManager.getLastKnownLocation(String provider), it gets null. Obviously, because there IS no last known location. It gets stuck before knowing one!
I have tried sending the coordinates through telnet as well. (cmd --> telnet localhost 5554 --> geo fix . But the same thing happens.
I have tried starting the device independent of the application, sending the coordinates, and then starting the application. But the same thing happens when I run the application: it hangs.
The following code HelloItemizedOverlay is taken from Android's MapView tutorial and works fine with manually given coordinates. The problem arises when GPS location is tried to be retrieved.
public class MyMapsActivity extends MapActivity
{
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
LinearLayout linLayout;
MapView mView;
List<Overlay> mapOverlays;
Drawable drawable;
HelloItemizedOverlay itemizedOverlay;
GeoUpdateHandler handler;
Location location;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
mView = (MapView) findViewById(R.id.mapview);
mView.setBuiltInZoomControls(true);
mapOverlays = mView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.icon);
itemizedOverlay = new HelloItemizedOverlay(drawable);
mapController = mView.getController();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
handler = new GeoUpdateHandler();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, handler);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
GeoPoint point = new GeoPoint((int)location.getLongitude(),(int)location.getLatitude());
OverlayItem overlayitem = new OverlayItem(point, "", "");
mView.setBuiltInZoomControls(true);
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
mapController.setZoom(8);
mapController.animateTo(point);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
public class GeoUpdateHandler implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
#Override
protected void onResume()
{
handler = new GeoUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, handler);
super.onResume();
}
}

According to this, the Geopoint constructor takes (latitude * 1e6, longitude * 1e6) as parameters ; whereas you put (longitude, latitude) when calling getLastKnownLocation, and you forgot the scale factor in the other call (in onLocationChanged). Latitude and logitude are not scaled in Location objects.
Anyways, this error should only result in displaying a blue map ((0,0) being in the atlantic ocean), so there may be other problems.
Edit:
1/ in replay to your comment, if you mix up longitude and latitude, you may get an unexisting point (latitude always stays within [-90°,90°] whereas longitude can vary in [-180°,180°])
2/ there is a bug in SDK 2.3 (API level 9), which makes the emulator crash when sending mock locations. Don't know wether it is true for 2.3.3 (lvl 10), but I used 2.1u1 (lvl 7) to test.
3/ The following code works for me :
package test.testmap;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MyMapsActivity extends MapActivity
{
private MapController mapController;
private LocationManager locationManager;
LinearLayout linLayout;
MapView mView;
List<Overlay> mapOverlays;
Drawable drawable;
HelloItemizedOverlay itemizedOverlay;
GeoUpdateHandler handler;
Location location;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
drawable = this.getResources().getDrawable(R.drawable.icon);
itemizedOverlay = new HelloItemizedOverlay(drawable);
mView = (MapView) findViewById(R.id.mapview);
mView.setBuiltInZoomControls(true);
mapOverlays = mView.getOverlays();
mapOverlays.add(itemizedOverlay);
mapController = mView.getController();
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
public class GeoUpdateHandler implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
Log.d(this.getClass().getName(),"onLocationChanged : lat = "+location.getLatitude()+" lon = "+location.getLongitude());
int lat = (int) Math.round(location.getLatitude()*1.0e6);
int lng = (int) Math.round(location.getLongitude()*1.0e6);
GeoPoint point = new GeoPoint(lat, lng);
itemizedOverlay.addOverlay(new OverlayItem(point, "", ""));
mapController.animateTo(point);
mapController.setZoom(8);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d(this.getClass().getName(),"onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d(this.getClass().getName(),"onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.d(this.getClass().getName(),"onStatusChanged");
}
}
#Override
protected void onResume()
{
handler = new GeoUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, handler);
super.onResume();
}
}

Related

how do i implement android mapbox android sdk successfully in fragment

I am using mapbox in a fragment with bottom navigation, when i exit and resume the app or when i change tabs rapidly, the app crashes. this is the error i get
10-07 22:20:36.046 21867-21886/com.dropexpress.driver.dropexpressdriver E/Mbgl-FileSource: Failed to read the storage key:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String, boolean)' on a null object reference
at com.mapbox.mapboxsdk.storage.FileSource.getCachePath(FileSource.java:88)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:165)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:155)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
the below code always fails when i exit the app and resume, or when i change tabs rapidly, i am using bottom navigation.
Steps to reproduce
here is my fragment code
package com.dropexpress.driver.dropexpressdriver.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dropexpress.driver.dropexpressdriver.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
public class HomeFragment extends Fragment {
private MapView mapView;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
Mapbox.getInstance(requireActivity(), "pk.eyJ1Ijoic3ludGF4bHRkIiwiYSI6ImNqaDJxNnhzbDAwNnMyeHF3dGlqODZsYjcifQ.pcz6BWpzCHeZ6hQg4AH9ww");
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Android versions: 5.0 +
Device models: motorola g5
Mapbox SDK versions: 6.5.0
Put your Mapbox.getInstance before inflating your layout.
Mapbox.getInstance(requireActivity(),"Your Map Key");
View view = inflater.inflate(R.layout.fragment_home, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
I hope this helps you.
i opened this issue in github, you check their response here
https://github.com/mapbox/mapbox-gl-native/issues/13044#issuecomment-427861016
this was their response:
I can see 2 issues with the provided code:
You are not calling MapView#onDestroy, this has to be called from you fragment's #onDestroyView.
MapView#onCreate should be called from fragment's #onViewCreatedinstead of #onCreateView.
I applied the changes and it worked!

SupportMapFragmentManagers getMapAsync() does not trigger onMapReady(GoogleMap map)

I have a
public abstract class MyMapFragment implements OnMapReadyCallback
{
//
public GoogleMap googleMap;
SupportMapFragment mapFragment;
#IdRes
public abstract int getSupportMapFragId();
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// http://stackoverflow.com/a/36592000/5102206
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// Do something for lollipop and above versions
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(getSupportMapFragId());
} else {
// do something for phones running an SDK before lollipop
mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(getSupportMapFragId());
}
mapFragment.getMapAsync(this);
}
//..
#Override
public void onMapReady(GoogleMap map) {
this.googleMap = map;
}
}
According to my breakpoints onViewCreated() is called, but onMapReady() is not called (breakpoint on this.googleMap = map not triggered)
On Android 5, 6 and 7 it works fine so far and I can see the Map..
On Android 4.X (API 16 - API 19) devices my app starts up, but then it seem to freeze there... I see a white blank screen.
On Android 4.X OS devices:
1. With getFragmentManager(), the mapFragment object is null after the else condition.
2. With getChildFragmentMenager() the mapfragment seem to be valid and non-null, but onMapReady not triggered.
What am I missing here?
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically
If you want to inflate a map in a fragment you can either do it in xml or do it in java code like this:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentByTag("mapFragment");
if (mapFragment == null) {
mapFragment = new SupportMapFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.mapFragmentContainer, mapFragment, "mapFragment");
ft.commit();
fm.executePendingTransactions();
}
mapFragment.getMapAsync(callback);
}
And also the simple container
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Also, you don't need to implement the onMapReadyCallback in the class definition. Instead of callback you create a new OnMapReadyCallback() right there:
MapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
}
});
You also need these
MapView mMapView;
private GoogleMap googleMap;
I hope this helps somehow !
There was an issue with a blocking thread from RxJava on main thread. So it was not an Google Maps issue.
I don't quite understand why you are nesting fragments, specially because it can cause performance issues.
If you take a look at Google Samples, the Google Maps examples uses an Activity and SupportMapFragment:
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback, ConnectionCallbacks,
OnConnectionFailedListener {
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.d(TAG, result.getErrorMessage());
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
}

how to add multiple map markers in android app

i have Google map displayed complete in my app. but the problem is how to add multiple map markers in my app. for different locations? and i am try some coded from here to my problem but not work..
like this
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
}
You can call
LatLng latLng = new LatLng(double_lat, double_long);
mMap.addMarker(new MarkerOptions().position(latLng));
how many times you want
If you want to add and show markers on your map there tree good steps to do it :
1 - Create an ARRAYList(MarkerOptions) MarkerList
2 - Create a function that add marker to MarkerList
3- Create a function that add all marker from MarkerList to the map.
After Creating MarkerList , this is addMarkerToList()
public void AddMarkerToList(double latitude,double longitude , String Name)
{
//Add Marker using Object
//we put just latitude and longitude and tilte of the marker
MarkerList.add(new MarkerOptions().position(new LatLng(latitude,longitude)).title(Name));
In the end this is the last function :
public void showMarker()
{
for (int i=0 ;i<MarkerList.size();i++) {
mMap.addMarker(MarkerList.get(i));
}
}

Android: GoogleMap v2 ignores animate/move calls

I have a FragmentActivity with a GoogleMap inside. It correctly receives the user location in onLocationChanged, where I try to use the user location to center the map:
#Override
public void onLocationChanged(Location loc)
{
if (centerMap && mMap != null)
{
LatLng location = new LatLng(loc.getLatitude(), loc.getLongitude());
CameraPosition pos = new CameraPosition.Builder().target(location).zoom(12).build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(pos);
mMap.animateCamera(cu);
// centerMap = false;
Log.e(getClass().getSimpleName(), "lat = " + location.latitude + " long = " + location.longitude);
}
}
This code actually worked now and then (maybe only once), and only during a debug session where I put a breakpoint inside the if statement. I don't understand what's wrong. The onLocationChanged method gets called regularly, it logs the position it received, that implies it entered the if condition, but the map does not move an inch from the lat=0,long=0 initial position (Africa).
Any clues?
EDIT: I must have something badly broken in my code: even markers do not show up, here is how I add them to the map
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title("title")
.draggable(false)
.visible(true));
and the "My location" icon is not showing up either, even if I called
mMap.setMyLocationEnabled(true);
in onCreate(). Trying to exclude martians and such, I've already updated Eclipse, ADT and all the rest to the latest available versions.
For some reason (unknown to me), moving the map initialization from onCreate() into the first invocation of onLocationChange() did the trick. Now my onCreate() is simply
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.map_activity);
}
my onStart() is:
#Override
protected void onStart()
{
super.onStart();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
#Override
public void onConnected(Bundle arg0)
{
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
and my onLocationChange() is
#Override
public void onLocationChanged(Location loc)
{
if (mMap == null)
{
mapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.add(R.id.mapcontainer, mapFragment);
fragmentTransaction.commit();
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.setMyLocationEnabled(false);
LatLng location = new LatLng(loc.getLatitude(), loc.getLongitude());
CameraPosition pos = new CameraPosition.Builder().target(location).zoom(12).build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(pos);
mMap.animateCamera(cu);
if (mLocationClient.isConnected())
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
Log.e(getClass().getSimpleName(), "lat = " + location.latitude + " long = " + location.longitude);
}
}
It works, but now I have a different problem (the map seems to ignore touch events). I'm going to create a separate question for that.

Can the GPS in android emulator track my current position?

i have made a program to find the current location using GPS in android emulator that is working correctly , and is showing the correct latitudes and longitudes that i send from emulator control in eclipse, but is it possible that the GPS in the emulator could show my current location by itself , i.e. in a way track my location and show it by itself without having me to send it through the emulator control.
Here is the code:
package location.finder;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class LocationFinderActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager locationManager= (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new loclistener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
public class loclistener implements LocationListener {
public void onLocationChanged(Location location){
String loc ="Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude();
Toast.makeText( getApplicationContext(),loc,Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider , int status, Bundle extras)
{
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
}
}
i guess in orinigal mobile you need not do any thing as it has GPS hardware
but emulator has GPS "stub" but it is not a real piece of hardware embedded in your PC so it will not track your location by itself
it would be better if you provide
your "program to find the current location using GPS in android emulator that is working correctly , and is showing the correct latitudes and longitudes that i send from emulator control in eclipse"
so that we can see and tell further