Example usage for android.location LocationListener LocationListener

List of usage examples for android.location LocationListener LocationListener

Introduction

In this page you can find the example usage for android.location LocationListener LocationListener.

Prototype

LocationListener

Source Link

Usage

From source file:org.deviceconnect.android.deviceplugin.host.profile.HostGeolocationProfile.java

/**
 * ?????.//from w  w w  .  ja v  a  2  s. c  o m
 * @param accuracy .
 * @param response ?.
 */
private void getGPS(final boolean accuracy, final Intent response) {
    if (ActivityCompat.checkSelfPermission(getContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getContext(),
                    ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        MessageUtils.setIllegalDeviceStateError(response, "ACCESS_FINE_LOCATION permission not granted.");
        sendResponse(response);
        return;
    }

    Criteria criteria = new Criteria();
    if (accuracy) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }

    mLocationManager.requestSingleUpdate(mLocationManager.getBestProvider(criteria, true),
            new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Bundle position = createPositionObject(location);

                    DConnectProfile.setResult(response, DConnectMessage.RESULT_OK);
                    response.putExtra(GeolocationProfile.PARAM_POSITION, position);
                    sendResponse(response);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                    // NOP
                }

                @Override
                public void onProviderEnabled(String provider) {
                    // NOP
                }

                @Override
                public void onProviderDisabled(String provider) {
                    // NOP
                }
            }, Looper.getMainLooper());
}

From source file:de.madvertise.android.sdk.MadUtil.java

/**
 * Try to update current location. Non blocking call.
 * //from   w  ww  .j a v a 2s .c  o  m
 * @param context
 *            application context
 */
protected static void refreshCoordinates(Context context) {
    if (PRINT_LOG)
        Log.d(LOG, "Trying to refresh location");

    if (context == null) {
        if (PRINT_LOG)
            Log.d(LOG, "Context not set - quit location refresh");
        return;
    }

    // check if we need a regular update
    if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System.currentTimeMillis()) {
        if (PRINT_LOG)
            Log.d(LOG, "It's not time yet for refreshing the location");
        return;
    }

    synchronized (context) {
        // recheck, if location was updated by another thread while we paused
        if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System
                .currentTimeMillis()) {
            if (PRINT_LOG)
                Log.d(LOG, "Another thread updated the loation already");
            return;
        }

        boolean permissionCoarseLocation = context.checkCallingOrSelfPermission(
                android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean permissionFineLocation = context.checkCallingOrSelfPermission(
                android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

        // return (null) if we do not have any permissions
        if (!permissionCoarseLocation && !permissionFineLocation) {
            if (PRINT_LOG)
                Log.d(LOG, "No permissions for requesting the location");
            return;
        }

        // return (null) if we can't get a location manager
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            if (PRINT_LOG)
                Log.d(LOG, "Unable to fetch a location manger");
            return;
        }

        String provider = null;
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);

        // try to get coarse location first
        if (permissionCoarseLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // try to get gps location if coarse locatio did not work
        if (provider == null && permissionFineLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // still no provider, return (null)
        if (provider == null) {
            if (PRINT_LOG)
                Log.d(LOG, "Unable to fetch a location provider");
            return;
        }

        // create a finalized reference to the location manager, in order to
        // access it in the inner class
        final LocationManager finalizedLocationManager = locationManager;
        locationUpdateTimestamp = System.currentTimeMillis();
        locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
            public void onLocationChanged(Location location) {
                if (PRINT_LOG)
                    Log.d(LOG, "Refreshing location");
                currentLocation = location;
                locationUpdateTimestamp = System.currentTimeMillis();
                // stop draining battery life
                finalizedLocationManager.removeUpdates(this);
            }

            // not used yet
            public void onProviderDisabled(String provider) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        }, context.getMainLooper());
    }
}

From source file:org.y20k.trackbook.TrackerService.java

private LocationListener createLocationListener() {
    return new LocationListener() {
        public void onLocationChanged(Location location) {
            // check if the new location is better
            if (LocationHelper.isBetterLocation(location, mCurrentBestLocation)) {
                // save location
                mCurrentBestLocation = location;
            }//from www .  j a v a  2  s. co  m
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            LogHelper.v(LOG_TAG, "Location provider status change: " + provider + " | " + status);
        }

        public void onProviderEnabled(String provider) {
            LogHelper.v(LOG_TAG, "Location provider enabled: " + provider);
        }

        public void onProviderDisabled(String provider) {
            LogHelper.v(LOG_TAG, "Location provider disabled: " + provider);
        }
    };
}

From source file:org.smap.smapTask.android.activities.MainMapsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_map);//from  w  w w . j ava2 s. c  om
    onRetainCalled = false;
    mapComponent = new BasicMapComponent("ef0d3930a7b6c95bd2b32ed45989c61f507eb65ee43283.04602330",
            new AppContext(this), 1, 1, new WgsPoint(144.959, -37.818), 10);
    mapComponent.setMap(OpenStreetMap.MAPNIK);

    final MemoryCache memoryCache = new MemoryCache(10 * 1024 * 1024);
    final File cacheDir = new File("/sdcard/maps_lib_cache");
    if (!cacheDir.exists()) {
        cacheDir.mkdir();
    }
    final AndroidFileSystemCache fileSystemCache = new AndroidFileSystemCache(this, "network_cache", cacheDir,
            10 * 1024 * 1024);
    //        mapComponent.setNetworkCache(new CachingChain(new Cache[] { memoryCache, fileSystemCache }));
    mapComponent.setNetworkCache(fileSystemCache);

    storedMap = new StoredMap("x", "/sdcard/maps_lib_cache", true);
    final Image missing = Image.createImage(storedMap.getTileSize(), storedMap.getTileSize());
    final Graphics graphics = missing.getGraphics();
    graphics.setColor(0xFFCCCECC);
    graphics.fillRect(0, 0, storedMap.getTileSize(), storedMap.getTileSize());
    storedMap.setMissingTileImage(missing);

    FileSystem fs = new JSR75FileSystem();
    mapComponent.setFileSystem(fs);
    mapComponent.setErrorListener(new MyErrorListener());

    mapComponent.setPanningStrategy(new ThreadDrivenPanning());
    mapComponent.startMapping();
    mapComponent.looseFocusOnDrag(true);

    // Define the location marker
    icon = BitmapFactory.decodeResource(getResources(), R.drawable.user_marker);
    pMark = new PlaceIcon(Image.createImage(icon), icon.getWidth() / 2, icon.getHeight());

    // Define the completed task actual location marker
    taskDoneIcon = BitmapFactory.decodeResource(getResources(), R.drawable.task_done_marker);
    pMarkDone = new PlaceIcon(Image.createImage(taskDoneIcon), icon.getWidth() / 2, icon.getHeight());

    // get the mapview that was defined in main.xml
    mMapView = (MapView) findViewById(R.id.mapview);
    //registerForContextMenu(mMapView);

    // mapview requires a mapcomponent
    mMapView.setMapComponent(mapComponent);

    mapComponent.setOnMapElementListener(this);
    mMapView.setFocusable(true);

    ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);

    // set zoomcontrols listeners to enable zooming
    zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
        public void onClick(final View v) {
            mapComponent.zoomIn();
        }
    });

    zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
        public void onClick(final View v) {
            mapComponent.zoomOut();
        }
    });

    /*
     * Add a location listener
     */
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

            if (userPlace != null) {
                mapComponent.removePlace(userPlace);
            }

            // TODO check for accuracy, save previous location
            WgsPoint point = new WgsPoint(location.getLongitude(), location.getLatitude());
            userPlace = new Place(0, new PlaceLabel("Location"), pMark, point);
            mapComponent.addPlace(userPlace);
        }

        @Override
        public void onProviderDisabled(String arg0) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

    };

    mapComponent.setMiddlePoint(new WgsPoint(144.95987, -37.81819));
    mapComponent.setSmoothZoom(true);

}

From source file:com.cianmcgovern.android.ShopAndShare.Share.java

/**
 * //from  ww  w.  java 2  s.  c  o m
 * Gets the location using the LocationListener and sets the class wide
 * location variable with the latitude and longitude Only gets the location
 * once and removes the listener after that result is obtained
 * 
 */
public void getLocation() {

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location loc) {
            Log.v(Constants.LOG_TAG, "Got longitude: " + loc.getLongitude());
            Log.v(Constants.LOG_TAG, "Got latitude: " + loc.getLatitude());
            mLocation.setLongitude(loc.getLongitude());
            mLocation.setLatitude(loc.getLatitude());
            getAddress();
            mLocationManager.removeUpdates(this);
            mSearch.setEnabled(true);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

    };

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.FanWallPlugin.java

private void initializeBackend() {
    // parse input xml data
    res = getResources();// w  ww.ja  va2  s  . c om
    density = res.getDisplayMetrics().density;

    showProgress = AnimationUtils.loadAnimation(FanWallPlugin.this, R.anim.show_progress_anim);
    hideProgress = AnimationUtils.loadAnimation(FanWallPlugin.this, R.anim.hide_progress_anim);

    currentIntent = getIntent();
    widget = (Widget) currentIntent.getSerializableExtra("Widget");
    String tempCachePath = widget.getCachePath();

    EntityParser parser = new EntityParser();
    try {
        if (TextUtils.isEmpty(widget.getPluginXmlData())) {
            if (TextUtils.isEmpty(currentIntent.getStringExtra("WidgetFile"))) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 3000);
                return;
            }
        }

        if (!TextUtils.isEmpty(widget.getPluginXmlData())) {
            parser.parse(widget.getPluginXmlData());
        } else {
            String xmlData = readXmlFromFile(currentIntent.getStringExtra("WidgetFile"));
            parser.parse(xmlData);
        }
    } catch (Exception e) {
        handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 3000);
        return;
    }

    Statics.hasAd = widget.isHaveAdvertisement();
    Statics.appName = widget.getAppName();
    Statics.near = parser.getNear();
    Statics.MODULE_ID = parser.getModuleId();
    Statics.canEdit = parser.getCanEdit();
    Statics.APP_ID = parser.getAppId();

    Statics.color1 = parser.getColor1();
    Statics.color2 = parser.getColor2();
    Statics.color3 = parser.getColor3();
    Statics.color4 = parser.getColor4();
    Statics.color5 = parser.getColor5();
    if (Statics.BackColorToFontColor(Statics.color1) == Color.WHITE)
        Statics.isSchemaDark = true;
    else
        Statics.isSchemaDark = false;

    // init cache path
    if (!TextUtils.isEmpty(tempCachePath))
        Statics.cachePath = tempCachePath + "/fanwall-" + widget.getOrder();

    Statics.onAuthListeners.add(this);

    // register separate LocationManager.GPS_PROVIDER for register status change events
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Statics.currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Statics.currentLocation = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
            Prefs.with(FanWallPlugin.this).save(Prefs.KEY_GPS, true);
            enableGpsCheckbox.setChecked(true);
        }

        @Override
        public void onProviderDisabled(String s) {
            Prefs.with(FanWallPlugin.this).save(Prefs.KEY_GPS, false);
            enableGpsCheckbox.setChecked(false);
        }
    });
}

From source file:org.phillyopen.mytracks.cyclephilly.MainInput.java

/** Called when the activity is first created. */
@Override//from w ww . j  a v a2  s  .  c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);

    final Firebase ref = new Firebase("https://cyclephilly.firebaseio.com");
    final Firebase phlref = new Firebase("https://phl.firebaseio.com");
    // Let's handle some launcher lifecycle issues:
    // If we're recording or saving right now, jump to the existing activity.
    // (This handles user who hit BACK button while recording)
    setContentView(R.layout.main);
    weatherFont = Typeface.createFromAsset(getAssets(), "cyclephilly.ttf");

    weatherText = (TextView) findViewById(R.id.weatherView);
    weatherText.setTypeface(weatherFont);
    weatherText.setText(R.string.cloudy);

    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            int state = rs.getState();
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(MainInput.this, SaveTrip.class));
                } else { // RECORDING OR PAUSED:
                    startActivity(new Intent(MainInput.this, RecordingActivity.class));
                }
                MainInput.this.finish();
            } else {
                // Idle. First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                String anon = settings.getString("" + PREF_ANONID, "NADA");

                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                } else if (anon == "NADA") {
                    showWelcomeDialog();
                }
                // Not first run - set up the list view of saved trips
                ListView listSavedTrips = (ListView) findViewById(R.id.ListSavedTrips);
                populateList(listSavedTrips);
            }
            MainInput.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // And set up the record button
    final Button startButton = (Button) findViewById(R.id.ButtonStart);
    final Intent i = new Intent(this, RecordingActivity.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    SharedPreferences settings = getSharedPreferences("PREFS", 0);
    final String anon = settings.getString("" + PREF_ANONID, "NADA");

    Firebase weatherRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia");
    Firebase tempRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia/currently");

    tempRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object val = dataSnapshot.getValue();
            String cardinal = null;

            TextView tempState = (TextView) findViewById(R.id.temperatureView);
            //                TextView liveTemp = (TextView) findViewById(R.id.warning);
            String apparentTemp = ((Map) val).get("apparentTemperature").toString();
            String windSpeed = ((Map) val).get("windSpeed").toString();
            Double windValue = (Double) ((Map) val).get("windSpeed");
            Long windBearing = (Long) ((Map) val).get("windBearing");

            //                liveTemp.setText(" "+apparentTemp.toString()+DEGREE);
            WindDirection[] windDirections = WindDirection.values();
            for (int i = 0; i < windDirections.length; i++) {
                if (windDirections[i].startDegree < windBearing && windDirections[i].endDegree > windBearing) {
                    //Get Cardinal direction
                    cardinal = windDirections[i].cardinal;
                }
            }

            if (windValue > 4) {
                tempState.setTextColor(0xFFDC143C);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph. Ride with caution.");
            } else {
                tempState.setTextColor(0xFFFFFFFF);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph.");
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                System.out.println("connected " + dataSnapshot.toString());
                Firebase cycleRef = new Firebase(FIREBASE_REF + "/" + anon + "/connections");
                //                    cycleRef.setValue(Boolean.TRUE);
                //                    cycleRef.onDisconnect().removeValue();
            } else {
                System.out.println("disconnected");
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            // No-op
        }
    });
    weatherRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Object value = snapshot.getValue();
            Object hourly = ((Map) value).get("currently");
            String alert = ((Map) hourly).get("summary").toString();
            //                TextView weatherAlert = (TextView) findViewById(R.id.weatherAlert);
            //                weatherAlert.setText(alert);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Acquire a reference to the system Location Manager
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            mySpot = new LatLng(location.getLatitude(), location.getLongitude());
            makeUseOfNewLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    nearbyStations = (RecyclerView) findViewById(R.id.nearbyStationList);
    nearbyStations.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    //Listener for Indego Changes
    indegoRef = new Firebase("https://phl.firebaseio.com/indego/kiosks");
    indegoRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Updates! Add them to indego data list
            indegoDataList = dataSnapshot;

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Register the listener with the Location Manager to receive location updates

    indegoGeofireRef = new Firebase("https://phl.firebaseio.com/indego/_geofire");
    GeoFire geoFire = new GeoFire(indegoGeofireRef);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    mySpot = myCurrentLocation();
    indegoList = new ArrayList<IndegoStation>();
    System.out.println("lo: " + mySpot.toString());

    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mySpot.longitude, mySpot.latitude), 0.5);
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            System.out.println(String.format("Key %s entered the search area at [%f,%f]", key,
                    location.latitude, location.longitude));
            //Create Indego Station object. To-do: check if object exists
            IndegoStation station = new IndegoStation();
            station.kioskId = key;
            station.location = location;
            if (indegoDataList != null) {
                //get latest info from list
                station.name = (String) indegoDataList.child(key).child("properties").child("name").getValue();
            }
            System.out.println(station.name);
            indegoList.add(station);
            //To-do: Add indego station info to RideIndegoAdapter

        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {
            System.out.println("GEO READY :" + indegoList.toString());
            indegoAdapter = new RideIndegoAdapter(getApplicationContext(), indegoList);
            nearbyStations.setAdapter(indegoAdapter);

        }

        @Override
        public void onGeoQueryError(FirebaseError error) {
            System.out.println("GEO error");
        }
    });

    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            } else {
                startActivity(i);
                MainInput.this.finish();
            }
        }
    });

    toolbar = (Toolbar) findViewById(R.id.dashboard_bar);
    toolbar.setTitle("Cycle Philly");

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
}

From source file:org.opensmc.mytracks.cyclesmc.MainInput.java

/** Called when the activity is first created. */
@Override//from w  w  w. ja  va 2s  .com
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);

    final Firebase ref = new Firebase("https://org.opensmc.mytracks.cyclesmc.firebaseio.com");
    final Firebase phlref = new Firebase("https://phl.firebaseio.com");
    // Let's handle some launcher lifecycle issues:
    // If we're recording or saving right now, jump to the existing activity.
    // (This handles user who hit BACK button while recording)
    setContentView(R.layout.main);
    weatherFont = Typeface.createFromAsset(getAssets(), "cyclesmc.ttf");

    weatherText = (TextView) findViewById(R.id.weatherView);
    weatherText.setTypeface(weatherFont);
    weatherText.setText(R.string.cloudy);

    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            int state = rs.getState();
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(MainInput.this, SaveTrip.class));
                } else { // RECORDING OR PAUSED:
                    startActivity(new Intent(MainInput.this, RecordingActivity.class));
                }
                MainInput.this.finish();
            } else {
                // Idle. First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                String anon = settings.getString("" + PREF_ANONID, "NADA");

                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                } else if (anon == "NADA") {
                    showWelcomeDialog();
                }
                // Not first run - set up the list view of saved trips
                ListView listSavedTrips = (ListView) findViewById(R.id.ListSavedTrips);
                populateList(listSavedTrips);
            }
            MainInput.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // And set up the record button
    final Button startButton = (Button) findViewById(R.id.ButtonStart);
    final Intent i = new Intent(this, RecordingActivity.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    SharedPreferences settings = getSharedPreferences("PREFS", 0);
    final String anon = settings.getString("" + PREF_ANONID, "NADA");

    Firebase weatherRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia");
    Firebase tempRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia/currently");

    tempRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object val = dataSnapshot.getValue();
            String cardinal = null;

            TextView tempState = (TextView) findViewById(R.id.temperatureView);
            //                TextView liveTemp = (TextView) findViewById(R.id.warning);
            String apparentTemp = ((Map) val).get("apparentTemperature").toString();
            String windSpeed = ((Map) val).get("windSpeed").toString();
            Double windValue = (Double) ((Map) val).get("windSpeed");
            Long windBearing = (Long) ((Map) val).get("windBearing");

            //                liveTemp.setText(" "+apparentTemp.toString()+DEGREE);
            WindDirection[] windDirections = WindDirection.values();
            for (int i = 0; i < windDirections.length; i++) {
                if (windDirections[i].startDegree < windBearing && windDirections[i].endDegree > windBearing) {
                    //Get Cardinal direction
                    cardinal = windDirections[i].cardinal;
                }
            }

            if (windValue > 4) {
                tempState.setTextColor(0xFFDC143C);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph. Ride with caution.");
            } else {
                tempState.setTextColor(0xFFFFFFFF);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph.");
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                System.out.println("connected " + dataSnapshot.toString());
                //                    Firebase cycleRef = new Firebase(FIREBASE_REF+"/"+anon+"/connections");
                //                    cycleRef.setValue(Boolean.TRUE);
                //                    cycleRef.onDisconnect().removeValue();
            } else {
                System.out.println("disconnected");
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            // No-op
        }
    });
    weatherRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Object value = snapshot.getValue();
            Object hourly = ((Map) value).get("currently");
            String alert = ((Map) hourly).get("summary").toString();
            //                TextView weatherAlert = (TextView) findViewById(R.id.weatherAlert);
            //                weatherAlert.setText(alert);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Acquire a reference to the system Location Manager
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            mySpot = new LatLng(location.getLatitude(), location.getLongitude());
            makeUseOfNewLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    //nearbyStations = (RecyclerView) findViewById(R.id.nearbyStationList);
    //nearbyStations.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    //Listener for Indego Changes
    /*indegoRef = new Firebase("https://phl.firebaseio.com/indego/kiosks");
    indegoRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //Updates! Add them to indego data list
        indegoDataList = dataSnapshot;
            
            
    }
            
    @Override
    public void onCancelled(FirebaseError firebaseError) {
            
    }
    });*/

    // Register the listener with the Location Manager to receive location updates

    //indegoGeofireRef = new Firebase("https://phl.firebaseio.com/indego/_geofire");
    //GeoFire geoFire = new GeoFire(indegoGeofireRef);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    mySpot = myCurrentLocation();
    //indegoList = new ArrayList<IndegoStation>();
    System.out.println("lo: " + mySpot.toString());

    /* GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mySpot.latitude,mySpot.longitude), 0.5);
     geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
        //Create Indego Station object. To-do: check if object exists
       // IndegoStation station = new IndegoStation();
        //station.kioskId = key;
        //station.location = location;
       /* if(indegoDataList != null){
            //get latest info from list
            station.name = (String) indegoDataList.child(key).child("properties").child("name").getValue();
        }
        System.out.println(station.name);
        //indegoList.add(station);
        //To-do: Add indego station info to RideIndegoAdapter
            
    }
            
    @Override
    public void onKeyExited(String key) {
            
    }
            
    @Override
    public void onKeyMoved(String key, GeoLocation location) {
            
    }
            
    @Override
        /* public void onGeoQueryReady() {
        //System.out.println("GEO READY :"+indegoList.toString());
       // indegoAdapter = new RideIndegoAdapter(getApplicationContext(),indegoList);
        //nearbyStations.setAdapter(indegoAdapter);
            
            
    }
            
    @Override
    public void onGeoQueryError(FirebaseError error) {
        System.out.println("GEO error");
    }
     });*/

    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            } else {
                startActivity(i);
                MainInput.this.finish();
            }
        }
    });

    toolbar = (Toolbar) findViewById(R.id.dashboard_bar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
}

From source file:com.google.android.dialer.provider.DialerProvider.java

private Location getLastLocation() {
    LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestSingleUpdate(new Criteria(), new LocationListener() {
        @Override// www.ja  va2s  . c  o  m
        public void onLocationChanged(Location location) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onLocationChanged: " + location);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onProviderDisabled: " + provider);
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onProviderEnabled: " + provider);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onStatusChanged: " + provider + ", " + status + ", " + extras);
            }
        }
    }, DialerProvider.mLooper);
    return locationManager.getLastLocation();
}