/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java
ViewVC logotype

Diff of /android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

android/TrainInfo/src/dk/thoerup/traininfo/StationLocator.java revision 252 by torben, Mon Aug 10 10:49:43 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java revision 1142 by torben, Tue Sep 28 14:58:45 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
 import java.util.ArrayList;  
3  import java.util.List;  import java.util.List;
4    
 import org.json.JSONArray;  
 import org.json.JSONObject;  
   
5  import android.content.Context;  import android.content.Context;
6  import android.location.Criteria;  import android.location.GpsSatellite;
7    import android.location.GpsStatus;
8  import android.location.Location;  import android.location.Location;
9  import android.location.LocationListener;  import android.location.LocationListener;
10  import android.location.LocationManager;  import android.location.LocationManager;
 import android.location.LocationProvider;  
11  import android.os.Bundle;  import android.os.Bundle;
12  import android.os.Handler;  import android.os.Handler;
13    import android.os.Message;
14  import android.util.Log;  import android.util.Log;
 import dk.thoerup.traininfo.util.DownloadUtil;  
15    
16  public class StationLocator implements LocationListener{  
17    public class LocationLookup implements LocationListener, GpsStatus.Listener {
18    
19          LocationManager locManager;          LocationManager locManager;
20          Context cntx;          Context cntx;
21          Handler hndl;          Handler hndl;
22    
23          ArrayList<StationBean> stationList = new ArrayList<StationBean>();          Location lastKnownLocation = null;
         List<StationBean> safeStationList = java.util.Collections.unmodifiableList(stationList);  
   
           
24          Location savedLocation = null;          Location savedLocation = null;
25            
26            boolean isSearching = false;
27            boolean hasGps;
28    
29          public StationLocator(Context c, Handler h) {          public LocationLookup(Context c, Handler h) {
30                  cntx = c;                  cntx = c;
31                  hndl = h;                  hndl = h;
32          }          }
33                    
34          public List<StationBean> getStations() {          
35                  return safeStationList;          public boolean hasLocation() {
36                    return savedLocation != null;
37            }
38            
39            public Location getLocation()
40            {
41                    return savedLocation;
42          }          }
43                    
44          public void abortLocationListener() {          public Location getLastKnownLocation() {
45                  locManager.removeUpdates(this);                  return lastKnownLocation;
46          }          }
47    
48          public void locateStations() {          public void locateStations() {
                 //http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&lstkp=0&rsz=small&hl=en&source=gsc&gss=.com&sig=fadf0e8d483d0f70bea11d5905010a16&q=Train%20station&near=56.377424%2C9.656695&key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q&v=1.0&nocache=1249640467498  
   
                 locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);  
                 /*//testcode  
                 List<String> provs = locManager.getAllProviders();  
                 for (String p  : provs) {  
                         Log.e("Provider", p);  
                 }  
                 provs = locManager.getProviders(true);  
                 for (String p  : provs) {  
                         Log.e("ActiveProvider", p);  
                 }  
                 */  
                 Criteria c = new Criteria();  
                 c.setAccuracy(Criteria.ACCURACY_FINE);  
                 String bestProv = locManager.getBestProvider(c, true);  
                 Log.i("BestProvider", ""+bestProv);  
49                                    
50                    isSearching = true;
51                    
52                    hasGps = false;
53                    locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);
54    
55                  if (bestProv != null) {                  List<String> providers = locManager.getProviders(true);        
56                          savedLocation = locManager.getLastKnownLocation(bestProv);                  
57                          locManager.requestLocationUpdates(bestProv, 0, 0, this);                  if (providers.size() > 0) {
58                            for(String provider : providers) {
59                                    Log.i("Provider", ""+provider);
60                                    if (provider.equalsIgnoreCase("gps")) {
61                                            locManager.addGpsStatusListener(this);
62                                            hasGps = true;                                  
63                                    }
64    
65                                    locManager.requestLocationUpdates(provider, 0, 0, this);
66                                    Location tmpLastKnown = locManager.getLastKnownLocation(provider);
67                                    if (tmpLastKnown != null) {
68                                            saveLastKnownLocation(tmpLastKnown);
69                                    }
70                            }
71                  } else {                  } else {
72                          // message that no suitable provider was found                          // message that no suitable provider was found
73                          hndl.sendEmptyMessage(TrainInfoList.NOPROVIDER);                          //hndl.sendEmptyMessage(StationList.NOPROVIDER);
74                            hndl.sendEmptyMessage(StationList.LookupStates.NOPROVIDER.ordinal());
75                            
76                  }                  }
77          }          }
78          @Override          @Override
79          public void onLocationChanged(Location location) {          public void onLocationChanged(Location location) {
80                    if (isSearching == false)
81                            return;
82                    
83                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());
84                    
85    
86                  savedLocation = new Location(location); //save a copy                  if (savedLocation == null || location.getAccuracy() < savedLocation.getAccuracy())
87                            savedLocation = new Location(location); //save a copy
88                                    
89                  if (location.getProvider().equals("gps") && location.getAccuracy() > 100) //if we have a gps provider lets wait for a more precise fix                  if (hasGps) {
90                          return;                          if (!location.getProvider().equals("gps")) {
91                                    return; // at least give the gps a chance
92                            } else if (location.getAccuracy() > 512) {
93                                    return; //if we have a gps provider lets wait for a more precise fix
94                            }
95    
96                  locManager.removeUpdates(this);                  }
97                  hndl.sendEmptyMessage(TrainInfoList.GOTLOCATION);                  stopSearch();
98                    hndl.sendEmptyMessage(StationList.LookupStates.GOTLOCATION.ordinal());
99          }          }
100                    
101          public void findNearestStations() {          private void saveLastKnownLocation(Location loc) {
102                  findNearestStations(savedLocation);                  if (lastKnownLocation == null) {
103                            lastKnownLocation = loc;
104                    } else {
105                            if (loc.getTime() > lastKnownLocation.getTime()) {//if loc is more recent than saved
106                                    lastKnownLocation = loc;
107                            }
108                    }
109          }          }
110                    
111          public void findNearestStations(Location location) {          public void stopSearch()
112                  //ToDo: to be nice put the api key into the request          {
113                  String urlSource = "http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&q=Train%20station&near=" + location.getLatitude() + "%2C" + location.getLongitude() + "&v=1.0";                  if (isSearching) {
114                  //String urlSource = "http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&q=Train%20station&near=56.2%2C9.0&v=1.0";                          isSearching = false;
115                            locManager.removeGpsStatusListener(this);
116                  try {                          locManager.removeUpdates(this);
                         String data = DownloadUtil.getContent(urlSource, 30000, "UTF-8");  
                         StringBuilder builder = new StringBuilder(data);  
   
                         while (builder.charAt(0) != '{')  
                                 builder.deleteCharAt(0);  
                         while (builder.charAt(builder.length()-1) != '}')  
                                 builder.deleteCharAt(builder.length()-1);  
   
                         JSONObject json = new JSONObject(builder.toString());  
                         // now have some fun with the results...  
                         JSONArray res = json.getJSONArray("results");  
   
                         Location tmpLocation = new Location("gps");  
                         stationList.clear();  
                           
                         for (int i=0; i<res.length(); i++) {  
                                 JSONObject jsonStation = res.getJSONObject(i);  
   
                                 double lat = jsonStation.getDouble("lat");  
                                 double lng = jsonStation.getDouble("lng");  
                                 String title = jsonStation.getString("title");  
                                 String addr = jsonStation.getString("streetAddress");  
                                 tmpLocation.setLatitude(lat);  
                                 tmpLocation.setLongitude(lng);  
   
                                 float distance = location.distanceTo(tmpLocation);  
   
                                 stationList.add( new StationBean(title,lat,lng,(int)distance,addr) );  
   
                                 Log.e("Location", title + " " + lat +"," + lng);  
                         }  
                         hndl.sendEmptyMessage(TrainInfoList.GOTSTATIONLIST);  
   
                 } catch (Exception e) {  
                         Log.e("Location","Location",e);  
                         hndl.sendEmptyMessage(TrainInfoList.LOOKUPSTATIONFAILED);  
117                  }                  }
                           
118          }          }
119    
120    
121          @Override          @Override
122          public void onProviderDisabled(String provider) {          public void onProviderDisabled(String provider) {
                 // TODO Auto-generated method stub  
   
123          }          }
124    
125    
126          @Override          @Override
127          public void onProviderEnabled(String provider) {          public void onProviderEnabled(String provider) {
                 // TODO Auto-generated method stub  
   
128          }          }
129    
130    
# Line 154  public class StationLocator implements L Line 134  public class StationLocator implements L
134    
135          }          }
136    
137          public static void injectMockLocation(Context cntx) {  
138                  Location odder = new Location("gps2");          @Override //GpsStatus.Listener
139                  odder.setLatitude(55.976632);          public void onGpsStatusChanged(int event) {
140                  odder.setLongitude(10.16407);                  if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
141                                            int count = 0;
142                  Location kbh = new Location("gps2"); //Christiansborg 55.675092,12.578573                          GpsStatus status =  locManager.getGpsStatus(null);
143                  kbh.setLatitude(55.675092);                          for (GpsSatellite sat : status.getSatellites()) {
144                  kbh.setLongitude(12.578573);                                  count ++;
145                                            }
146                  LocationManager lm = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);                          
147                  if (lm.getProvider("gps2") == null)                          Message msg = new Message();
148                          lm.addTestProvider("gps2", false, true, true, false, false, false, false, 0, Criteria.ACCURACY_FINE );                          msg.what = StationList.LookupStates.GPS_SAT_COUNT.ordinal();
149                  lm.setTestProviderEnabled("gps2", true);                          msg.arg1 = count;
150                  lm.setTestProviderLocation("gps2", kbh);                          hndl.sendMessage(msg);
151          }                  }
152                            
         public static void removeMockLocation(Context cntx) {  
                 LocationManager lm = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);  
                 if (lm.getProvider("gps2") != null)  
                         lm.removeTestProvider("gps2");  
153          }          }
154  }  }

Legend:
Removed from v.252  
changed lines
  Added in v.1142

  ViewVC Help
Powered by ViewVC 1.1.20