/[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 238 by torben, Sat Aug 8 20:09:47 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java revision 488 by torben, Thu Oct 29 13:42:57 2009 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
 import java.io.BufferedReader;  
 import java.io.InputStreamReader;  
 import java.net.URL;  
 import java.net.URLConnection;  
 import java.util.ArrayList;  
3  import java.util.List;  import java.util.List;
4    
 import org.json.JSONArray;  
 import org.json.JSONObject;  
   
 import dk.thoerup.traininfo.util.DownloadUtil;  
   
5  import android.content.Context;  import android.content.Context;
 import android.location.Criteria;  
6  import android.location.Location;  import android.location.Location;
7  import android.location.LocationListener;  import android.location.LocationListener;
8  import android.location.LocationManager;  import android.location.LocationManager;
# Line 21  import android.os.Bundle; Line 10  import android.os.Bundle;
10  import android.os.Handler;  import android.os.Handler;
11  import android.util.Log;  import android.util.Log;
12    
13  public class StationLocator implements LocationListener{  
14    public class LocationLookup implements LocationListener{
15    
16          LocationManager locManager;          LocationManager locManager;
17          Context cntx;          Context cntx;
18          Handler hndl;          Handler hndl;
19    
20          ArrayList<StationBean> stationList = new ArrayList<StationBean>();          Location lastKnownLocation = null;
21          List<StationBean> safeStationList = java.util.Collections.unmodifiableList(stationList);          Location savedLocation = null;
22            
23            boolean isSearching = false;
24            boolean hasGps;
25    
26          public StationLocator(Context c, Handler h) {          public LocationLookup(Context c, Handler h) {
27                  cntx = c;                  cntx = c;
28                  hndl = h;                  hndl = h;
29          }          }
30                    
31          public List<StationBean> getStations() {          
32                  return safeStationList;          public boolean hasLocation() {
33                    return savedLocation != null;
34          }          }
35                    
36          public void abortLocationListener() {          public Location getLocation()
37                  locManager.removeUpdates(this);          {
38                    return savedLocation;
39            }
40            
41            public Location getLastKnownLocation() {
42                    return lastKnownLocation;
43          }          }
44    
45          public void locateStations() {          public void locateStations() {
46                  //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                  
47                    isSearching = true;
48                    
49                    hasGps = false;
50                  locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);                  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.e("BestProvider", bestProv);  
51    
52                  if (bestProv != null) {                  List<String> providers = locManager.getProviders(true);        
53                          locManager.requestLocationUpdates(bestProv, 0, 0, this);                  
54                    if (providers.size() > 0) {
55                            for(String provider : providers) {
56                                    Log.i("Provider", ""+provider);
57                                    if (provider.equalsIgnoreCase("gps"))
58                                            hasGps = true;
59                                    locManager.requestLocationUpdates(provider, 0, 0, this);
60                                    
61                                    saveLastKnownLocation(locManager.getLastKnownLocation(provider));
62                            }
63                  } else {                  } else {
64                          // message that no suitable provider was found                          // message that no suitable provider was found
65                          hndl.sendEmptyMessage(TrainInfoList.NOPROVIDER);                          hndl.sendEmptyMessage(StationList.NOPROVIDER);
66                  }                  }
67          }          }
68          @Override          @Override
69          public void onLocationChanged(Location location) {          public void onLocationChanged(Location location) {
70                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());                  if (isSearching == false)
   
                 if (location.getProvider().equals("gps") && location.getAccuracy() > 100) //if we have a gps provider lets wait for a more precise fix  
71                          return;                          return;
   
                 locManager.removeUpdates(this);  
                 hndl.sendEmptyMessage(TrainInfoList.GOTLOCATION);  
72                                    
73                  //ToDo: to be nice put the api key into the request                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());
74                  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";                  
                 //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";  
   
                 try {/*  
                         Log.e("Url", urlSource);  
                         URL url = new URL(urlSource);  
                         URLConnection connection = url.openConnection();  
                         connection.setConnectTimeout(10000);  
   
                         String line;  
                         StringBuilder builder = new StringBuilder();  
                         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 8192);  
                         while((line = reader.readLine()) != null) {  
                                 builder.append(line);  
                         }*/  
                         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) );  
75    
76                                  Log.e("Location", title + " " + lat +"," + lng);                  if (savedLocation == null || location.getAccuracy() < savedLocation.getAccuracy())
77                            savedLocation = new Location(location); //save a copy
78                    
79                    if (hasGps) {
80                            if (!location.getProvider().equals("gps")) {
81                                    return; // at least give the gps a chance
82                            } else if (location.getAccuracy() > 256) {
83                                    return; //if we have a gps provider lets wait for a more precise fix
84                          }                          }
                         hndl.sendEmptyMessage(TrainInfoList.GOTSTATIONLIST);  
85    
                 } catch (Exception e) {  
                         Log.e("Location","Location",e);  
                         hndl.sendEmptyMessage(TrainInfoList.LOOKUPSTATIONFAILED);  
86                  }                  }
87                                    stopSearch();
88                    hndl.sendEmptyMessage(StationList.GOTLOCATION);
89            }
90            
91            private void saveLastKnownLocation(Location loc) {
92                    if (lastKnownLocation == null) {
93                            lastKnownLocation = loc;
94                    } else {
95                            if (loc.getTime() > lastKnownLocation.getTime()) {//if loc is more recent than saved
96                                    lastKnownLocation = loc;
97                            }
98                    }
99            }
100            
101            public void stopSearch()
102            {
103                    if (isSearching) {
104                            isSearching = false;
105                            locManager.removeUpdates(this);
106                    }
107          }          }
108    
109    
110          @Override          @Override
111          public void onProviderDisabled(String provider) {          public void onProviderDisabled(String provider) {
                 // TODO Auto-generated method stub  
   
112          }          }
113    
114    
115          @Override          @Override
116          public void onProviderEnabled(String provider) {          public void onProviderEnabled(String provider) {
                 // TODO Auto-generated method stub  
   
117          }          }
118    
119    

Legend:
Removed from v.238  
changed lines
  Added in v.488

  ViewVC Help
Powered by ViewVC 1.1.20