Friday, August 31, 2012

Location service (android)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class LocationTestActivity extends Activity implements LocationListener {

    private LocationManager service;
    private TextView tv;
    private String provider;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        tv = (TextView) findViewById(R.id.display);
      
        // Get the location manager
        service = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = service.getBestProvider(criteria, false);
        Location location = service.getLastKnownLocation(provider);
      
        // Initialize the location fields
        if (location != null) {
          onLocationChanged(location);
        } else {
          tv.setText("Location not available");
        }
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!enabled) {
          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startActivity(intent);
        }
    }
    public void onLocationChanged(Location arg0) {
     
        //int lat = (int) (location.getLatitude());
        //int lng = (int) (location.getLongitude());
        //latituteField.setText(String.valueOf(lat));
        //longitudeField.setText(String.valueOf(lng));
     
        String lat = String.valueOf(arg0.getLatitude());
        String lon = String.valueOf(arg0.getLongitude());
        Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
        tv.setText("lat="+lat+", lon="+lon);
    }
    public void onProviderDisabled(String arg0) {
        Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
        Log.e("GPS", "provider disabled " + arg0);
    }
    public void onProviderEnabled(String arg0) {
        Toast.makeText(this, "Enabled new provider " + provider, Toast.LENGTH_SHORT).show();
        Log.e("GPS", "provider enabled " + arg0);
    }
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
    }
    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        service.requestLocationUpdates(provider, 400, 1, this);
    }
    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        service.removeUpdates(this);
    } 
}




No comments:

Post a Comment