Example usage for android.content Context LOCATION_SERVICE

List of usage examples for android.content Context LOCATION_SERVICE

Introduction

In this page you can find the example usage for android.content Context LOCATION_SERVICE.

Prototype

String LOCATION_SERVICE

To view the source code for android.content Context LOCATION_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.location.LocationManager for controlling location updates.

Usage

From source file:com.application.treasurehunt.ScanQRCodeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan_qrcode);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ActionBar actionBar = getActionBar();
        actionBar.setTitle("Treasure Hunt");
        actionBar.setSubtitle("Scan a QR code");
    }/*from  w w w .  j  a v a 2 s  .co  m*/

    mScanButton = (Button) findViewById(R.id.scan_qr_code_button);
    mQuestionReturned = (TextView) findViewById(R.id.scan_content_received);

    mMapManager = MapManager.get(this);
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    mMapDataSource = MapDataDAO.getInstance(this);
    mMapDataSource.open();

    mSettings = getSharedPreferences("UserPreferencesFile", 0);
    mEditor = mSettings.edit();

    //http://developer.android.com/guide/topics/data/data-storage.html#pref
    mCurrentHuntId = mSettings.getInt("currentHuntId", 0);
    mCurrentParticipantId = mSettings.getInt("huntParticipantId", 0);

    Log.i("ScanQRCode", "The hunt retrieved from the editor is: " + mCurrentHuntId);

    if (savedInstanceState == null) {
        checkLocationServices();
    }

    ScanQRCodeActivity.this.registerReceiver(mLocationReceiver, new IntentFilter(MapManager.ACTION_LOCATION));

    mScanButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mQuestionReturned.setText("");
            Intent intent = new Intent(ScanQRCodeActivity.this, ZBarScannerActivity.class);
            startActivityForResult(intent, 1);
        }
    });
}

From source file:com.example.mapdemo.MyLocationDemoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    instance = this;
    super.onCreate(savedInstanceState);

    setContentView(R.layout.my_location_demo);

    ButterKnife.bind(this);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
    mapFragment.getMapAsync(this);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;// ww w  .  j a  v a 2s.  co  m
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, new PositionListener());

    alarm = RingtoneManager.getRingtone(getApplicationContext(),
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            createDialogForProgrammedStop();
            handler.postDelayed(this, Constants.TIME);
        }
    }, Constants.TIME);

}

From source file:com.hqas.ridetracker.RideTrackerFragment.java

@Override
public void onResume() {
    super.onResume();

    locMan = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();
    crit.setAccuracy(Criteria.ACCURACY_FINE);
    locMan.requestLocationUpdates(0L, 0.0f, crit, tService, null);
    map.setLocationSource(tService);//from  ww  w  .j ava 2  s  .  com
    broadcastManager = LocalBroadcastManager.getInstance(getActivity());
    broadcastManager.registerReceiver(mapUpdateReceiver,
            new IntentFilter(TrackerService.ACTION_MAP_UPDATE_LOCATION));
    broadcastManager.registerReceiver(startStopReceiver,
            new IntentFilter(TrackerService.ACTION_START_STOP_RECEIVED));
    broadcastManager.registerReceiver(pebbleConnectedReceiver,
            new IntentFilter(TrackerService.ACTION_PEBBLE_CONNECTED));
    broadcastManager.registerReceiver(pebbleConnectedReceiver,
            new IntentFilter(TrackerService.ACTION_PEBBLE_DISCONNECTED));
    broadcastManager.registerReceiver(resetReceiver, new IntentFilter(TrackerService.ACTION_RESET_RECEIVED));

    if (PebbleKit.isWatchConnected(getActivity())) {
        PebbleKit.startAppOnPebble(getActivity(), MainActivity.PEBBLE_APP_UUID);
        pebbleConnected();
    } else {
        pebbleStatus.setText(res.getString(R.string.pebble_status_disconnected));
        pebbleDisconnected();
    }

}

From source file:de.grobox.liberario.DirectionsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // remember view for UI changes when fragment is not active
    mView = inflater.inflate(R.layout.fragment_directions, container, false);
    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    checkPreferences();/*from ww w  .jav a2s.c o  m*/

    setFromUI();
    setToUI();

    // timeView
    final Button timeView = (Button) mView.findViewById(R.id.timeView);
    timeView.setText(DateUtils.getcurrentTime(getActivity()));
    timeView.setTag(Calendar.getInstance());
    timeView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showTimePickerDialog();
        }
    });

    // set current time on long click
    timeView.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            timeView.setText(DateUtils.getcurrentTime(getActivity()));
            timeView.setTag(Calendar.getInstance());
            return true;
        }
    });

    Button plus10Button = (Button) mView.findViewById(R.id.plus15Button);
    plus10Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            addToTime(15);
        }
    });

    // dateView
    final Button dateView = (Button) mView.findViewById(R.id.dateView);
    dateView.setText(DateUtils.getcurrentDate(getActivity()));
    dateView.setTag(Calendar.getInstance());
    dateView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog();
        }
    });

    // set current date on long click
    dateView.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            dateView.setText(DateUtils.getcurrentDate(getActivity()));
            dateView.setTag(Calendar.getInstance());
            return true;
        }
    });

    // Trip Date Type Spinner (departure or arrival)
    final TextView dateType = (TextView) mView.findViewById(R.id.dateType);
    dateType.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (dateType.getText().equals(getString(R.string.trip_dep))) {
                dateType.setText(getString(R.string.trip_arr));
            } else {
                dateType.setText(getString(R.string.trip_dep));
            }
        }
    });

    // Products
    final ViewGroup productsLayout = (ViewGroup) mView.findViewById(R.id.productsLayout);
    for (int i = 0; i < productsLayout.getChildCount(); ++i) {
        final ImageView productView = (ImageView) productsLayout.getChildAt(i);
        final Product product = Product.fromCode(productView.getTag().toString().charAt(0));

        // make inactive products gray
        if (mProducts.contains(product)) {
            productView.getDrawable().setColorFilter(null);
        } else {
            productView.getDrawable().setColorFilter(getResources().getColor(R.color.highlight),
                    PorterDuff.Mode.SRC_ATOP);
        }

        // handle click on product icon
        productView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mProducts.contains(product)) {
                    productView.getDrawable().setColorFilter(getResources().getColor(R.color.highlight),
                            PorterDuff.Mode.SRC_ATOP);
                    mProducts.remove(product);
                    Toast.makeText(v.getContext(), LiberarioUtils.productToString(v.getContext(), product),
                            Toast.LENGTH_SHORT).show();
                } else {
                    productView.getDrawable().setColorFilter(null);
                    mProducts.add(product);
                    Toast.makeText(v.getContext(), LiberarioUtils.productToString(v.getContext(), product),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        // handle long click on product icon by showing product name
        productView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(view.getContext(), LiberarioUtils.productToString(view.getContext(), product),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    if (!Preferences.getPref(getActivity(), Preferences.SHOW_ADV_DIRECTIONS)) {
        (mView.findViewById(R.id.productsScrollView)).setVisibility(View.GONE);
    }

    Button searchButton = (Button) mView.findViewById(R.id.searchButton);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            NetworkProvider np = NetworkProviderFactory.provider(Preferences.getNetworkId(getActivity()));
            if (!np.hasCapabilities(NetworkProvider.Capability.TRIPS)) {
                Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_no_trips_capability),
                        Toast.LENGTH_SHORT).show();
                return;
            }

            AsyncQueryTripsTask query_trips = new AsyncQueryTripsTask(v.getContext());

            // check and set to location
            if (checkLocation(FavLocation.LOC_TYPE.TO)) {
                query_trips.setTo(getLocation(FavLocation.LOC_TYPE.TO));
            } else {
                Toast.makeText(getActivity(), getResources().getString(R.string.error_invalid_to),
                        Toast.LENGTH_SHORT).show();
                return;
            }

            // check and set from location
            if (mGpsPressed) {
                if (getLocation(FavLocation.LOC_TYPE.FROM) != null) {
                    query_trips.setFrom(getLocation(FavLocation.LOC_TYPE.FROM));
                } else {
                    mAfterGpsTask = query_trips;

                    pd = new ProgressDialog(getActivity());
                    pd.setMessage(getResources().getString(R.string.stations_searching_position));
                    pd.setCancelable(false);
                    pd.setIndeterminate(true);
                    pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mAfterGpsTask = null;
                                    dialog.dismiss();
                                }
                            });
                    pd.show();
                }
            } else {
                if (checkLocation(FavLocation.LOC_TYPE.FROM)) {
                    query_trips.setFrom(getLocation(FavLocation.LOC_TYPE.FROM));
                } else {
                    Toast.makeText(getActivity(), getString(R.string.error_invalid_from), Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
            }

            // remember trip if not from GPS
            if (!mGpsPressed) {
                FavDB.updateFavTrip(getActivity(), new FavTrip(getLocation(FavLocation.LOC_TYPE.FROM),
                        getLocation(FavLocation.LOC_TYPE.TO)));
            }

            // set date
            query_trips.setDate(DateUtils.mergeDateTime(getActivity(), dateView.getText(), timeView.getText()));

            // set departure to true of first item is selected in spinner
            query_trips.setDeparture(dateType.getText().equals(getString(R.string.trip_dep)));

            // set products
            query_trips.setProducts(mProducts);

            // don't execute if we still have to wait for GPS position
            if (mAfterGpsTask != null)
                return;

            query_trips.execute();
        }
    });

    return mView;
}

From source file:ca.ualberta.cs.cmput301w15t04team04project.EditClaimActivity.java

/**
 *///  w ww .j  av  a 2  s. c  o m

public void getClaimLocation(View view) {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener);
    claimLocation = location;

}

From source file:com.cloudbees.gasp.activity.GaspLocationsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    LocationManager locationManager;//ww w  .  j av  a 2  s.  c o  m
    String svcName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(svcName);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);
    Log.i(TAG, "CURRENT LOCATION");
    Log.i(TAG, "Latitude = " + location.getLatitude());
    Log.i(TAG, "Longitude = " + location.getLongitude());

    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Geocoder gc = new Geocoder(this, Locale.getDefault());

        if (!Geocoder.isPresent())
            Log.i(TAG, "No geocoder available");
        else {
            try {
                List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append(" ");

                    sb.append(address.getLocality()).append("");
                    sb.append(address.getPostalCode()).append(" ");
                    sb.append(address.getCountryName());
                }
                Log.i(TAG, "Address: " + sb.toString());
            } catch (IOException e) {
                Log.d(TAG, "IOException getting address from geocoder", e);
            }
        }
    }

    map.setMyLocationEnabled(true);

    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
    CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(16).bearing(0).tilt(0)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    new LocationMapper().execute();
}

From source file:com.metinkale.prayerapp.vakit.AddCity.java

@SuppressWarnings("MissingPermission")
public void checkLocation() {
    if (PermissionUtils.get(this).pLocation) {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Location loc = null;/*from   w  w w  .  ja v  a  2  s .c o  m*/
        List<String> providers = lm.getProviders(true);
        for (String provider : providers) {
            Location last = lm.getLastKnownLocation(provider);
            // one hour==1meter in accuracy
            if ((last != null) && ((loc == null)
                    || ((last.getAccuracy() - (last.getTime() / (1000 * 60 * 60))) < (loc.getAccuracy()
                            - (loc.getTime() / (1000 * 60 * 60)))))) {
                loc = last;
            }
        }

        if (loc != null)
            onLocationChanged(loc);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setSpeedRequired(false);
        String provider = lm.getBestProvider(criteria, true);
        if (provider != null) {
            lm.requestSingleUpdate(provider, this, null);
        }

    } else {
        PermissionUtils.get(this).needLocation(this);
    }
}

From source file:com.example.android.location.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your app and
 * process location updates.  The app also shows how to convert lat/long coordinates to
 * human-readable addresses.//from  ww  w .  j a v a 2  s  .co m
 */
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}

From source file:androidmapsdefinitivo.android.bajaintec.com.androidmapsdefinitivo.MapsActivity.java

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;/*w  w  w.  ja v a  2s  .  c  o  m*/

    try {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location == null) {
                Log.d("Falla de gps: ", "valio");
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }

        }
        CameraUpdate center = CameraUpdateFactory
                .newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
        /*
        CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(32.595085,
            -115.482046));
        */
        //CameraUpdate zoom = CameraUpdateFactory.zoomTo(20);
        mMap.moveCamera(center);
        //mMap.animateCamera(zoom);
        point = new LatLng(location.getAltitude(), location.getLongitude());
        getLines(location.getAltitude(), location.getLongitude());
        //getLines();
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(false);
    } catch (SecurityException e) {
        System.exit(0);
    } catch (NullPointerException e) {
        System.exit(0);
    }

    final Snackbar snackStart = Snackbar.make(findViewById(R.id.map), "Selecciona una ruta de una calle",
            Snackbar.LENGTH_LONG);

    snackStart.show();

    final Snackbar snackErr = Snackbar.make(findViewById(R.id.map), "Selecciona una sola calle",
            Snackbar.LENGTH_LONG);

    final Snackbar snackbar = Snackbar.make(findViewById(R.id.map), R.string.guardar_ruta,
            Snackbar.LENGTH_LONG);

    mBtnGuardar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MapsActivity.this, SeguridadActivity.class);
            intent.putExtra("calle", calleDestino);
            intent.putExtra("origen_n", String.valueOf(markerPoints.get(0).latitude));
            intent.putExtra("origen_w", String.valueOf(markerPoints.get(0).longitude));
            intent.putExtra("destino_n", String.valueOf(markerPoints.get(1).latitude));
            intent.putExtra("destino_w", String.valueOf(markerPoints.get(1).longitude));
            intent.putExtra("idUsuario", getIntent().getIntExtra("idUsuario", 0));
            startActivity(intent);
        }
    });

    mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            LatLng li = cameraPosition.target;
            LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;

            if (!bounds.contains(point)) {
                try {
                    point = null;
                    point = new LatLng(li.latitude, li.longitude);
                    System.out.println("Sali");
                    getLines(point.latitude, point.longitude);
                    //getLines();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {

            if (markerPoints.size() > 1) {
                markerPoints.clear();
                mMap.clear();
                mBtnGuardar.setEnabled(false);
                //snackbar.dismiss();
                getLines();
                //getLines(point.latitude,point.longitude);
            }

            markerPoints.add(point);
            /*
            try {
            Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses = gc.getFromLocation(point.latitude, point.longitude, 1);
            //Obtener nombres de las calles.
            if (markerPoints.size() == 1) {
                calleOrigen = addresses.get(0).getAddressLine(0);
            } else if (markerPoints.size() == 2) {
                calleDestino = addresses.get(0).getAddressLine(0);
            }
                    
            } catch (IOException e) {
            e.printStackTrace();
            }*/

            MarkerOptions options = new MarkerOptions();

            options.position(point);

            if (markerPoints.size() == 1) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            } else if (markerPoints.size() == 2) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                if (!calleOrigen.equalsIgnoreCase(calleDestino)) {
                    Log.d("Calles: ", calleOrigen + "//" + calleDestino);
                    Boolean msj = !calleOrigen.equalsIgnoreCase(calleDestino);
                    Log.d("Calles: ", msj.toString());
                    markerPoints.clear();
                    mMap.clear();
                    //getLines(point.latitude,point.longitude);
                    getLines();
                    snackErr.show();
                    return;
                }
            }

            mMap.addMarker(options);

            if (markerPoints.size() >= 2) {
                LatLng origin = markerPoints.get(0);
                LatLng dest = markerPoints.get(1);

                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                downloadTask.execute(url);
                snackbar.show();
                mBtnGuardar.setEnabled(true);
            }
        }

    });
    //getLines();
    getLines(point.latitude, point.longitude);
}

From source file:com.jesjimher.bicipalma.MesProperesActivity.java

/** Called when the activity is first created. */
@Override/*from   w  w w .  j  a  v a 2s  .c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mesproperes);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Si s'ha d'activar el wifi en inici, fer-ho
    WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    // Guardar el estado actual para restaurarlo al salir
    this.estatWifi = wm.isWifiEnabled();
    if (prefs.getBoolean("activarWifiPref", false))
        wm.setWifiEnabled(true);

    // Cargamos la versin cacheada de las estaciones
    leerCacheEstaciones();

    actualizarListado();

    // Iniciamos la descarga de las estaciones y su estado desde la web (en un thread aparte)
    descargaEstaciones = new RecuperarEstacionesTask(this);
    descargaEstaciones.execute();

    // Inicialmente se busca por red (ms rpido)
    //       dBuscaUbic=ProgressDialog.show(c, "",getString(R.string.buscandoubica),true,true);
    //        Toast.makeText(getApplicationContext(), "Activando", Toast.LENGTH_SHORT).show();
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    providerCoarse = locationManager.getBestProvider(criteria, true);

    if (providerCoarse == null) {
        Toast.makeText(getApplicationContext(), "No hay forma de posicionarse", Toast.LENGTH_SHORT).show();
        return;
    }
    locationManager.requestLocationUpdates(providerCoarse, 10, 0, (LocationListener) this);

    // Usar ltima ubicacin conocida de red para empezar y recibir futuras actualizaciones
    lBest = locationManager.getLastKnownLocation(providerCoarse);

    // Guardar el inicio de bsqueda de ubicacin para no pasarse de tiempo
    //tIni=new Date().getTime();
    tIni = System.currentTimeMillis();

    // Crear listeners para mostrar estacin en mapa, o abrir men con clic largo
    ListView lv = (ListView) findViewById(R.id.listado);
    lv.setOnItemClickListener((OnItemClickListener) this);
    lv.setOnItemLongClickListener((OnItemLongClickListener) this);
}