Example usage for android.location Location getSpeed

List of usage examples for android.location Location getSpeed

Introduction

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

Prototype

public float getSpeed() 

Source Link

Document

Get the speed if it is available, in meters/second over ground.

Usage

From source file:com.secupwn.aimsicd.service.CellTracker.java

/**
 * Add entries to the {@link com.secupwn.aimsicd.data.model.Measure Measure} realm
 *//*from  w  w w  .  j av  a 2  s .  c om*/
public void onLocationChanged(Location loc) {
    // TODO: See issue #555 (DeviceApi17.java is using API 18 CellInfoWcdma calls.
    if (Build.VERSION.SDK_INT > 17) {
        DeviceApi18.loadCellInfo(tm, device);
    }

    if (!device.cell.isValid()) {
        CellLocation cellLocation = tm.getCellLocation();
        if (cellLocation != null) {
            switch (device.getPhoneId()) {

            case TelephonyManager.PHONE_TYPE_NONE:
            case TelephonyManager.PHONE_TYPE_SIP:
            case TelephonyManager.PHONE_TYPE_GSM:
                GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
                device.cell.setCellId(gsmCellLocation.getCid()); // CID
                device.cell.setLocationAreaCode(gsmCellLocation.getLac()); // LAC
                device.cell.setPrimaryScramblingCode(gsmCellLocation.getPsc()); // PSC
                break;

            case TelephonyManager.PHONE_TYPE_CDMA:
                CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
                device.cell.setCellId(cdmaCellLocation.getBaseStationId()); // BSID ??
                device.cell.setLocationAreaCode(cdmaCellLocation.getNetworkId()); // NID
                device.cell.setSid(cdmaCellLocation.getSystemId()); // SID
                device.cell.setMobileNetworkCode(cdmaCellLocation.getSystemId()); // MNC <== BUG!??

                break;
            }
        }
    }

    if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
            && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {

        device.cell.setLon(loc.getLongitude()); // gpsd_lon
        device.cell.setLat(loc.getLatitude()); // gpsd_lat
        device.cell.setSpeed(loc.getSpeed()); // speed        // TODO: Remove, we're not using it!
        device.cell.setAccuracy(loc.getAccuracy()); // gpsd_accu
        device.cell.setBearing(loc.getBearing()); // -- [deg]??   // TODO: Remove, we're not using it!
        device.setLastLocation(loc); //

        // Store last known location in preference
        SharedPreferences.Editor prefsEditor;
        prefsEditor = prefs.edit();
        prefsEditor.putString(context.getString(R.string.data_last_lat_lon),
                String.valueOf(loc.getLatitude()) + ":" + String.valueOf(loc.getLongitude()));
        prefsEditor.apply();

        // This only logs a BTS if we have GPS lock
        // TODO: Is correct behaviour? We should consider logging all cells, even without GPS.
        if (trackingCell) {
            // This also checks that the locationAreaCode are cid are not in DB before inserting
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            dbHelper.insertBTS(realm, device.cell);
        }
    }
}

From source file:com.nextgis.mobile.fragment.MapFragment.java

private void fillTextViews(Location location) {
    if (null == location) {
        setDefaultTextViews();//  www  .j a va 2 s . c om
    } else {
        if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
            String text = "";
            int satellites = location.getExtras() != null ? location.getExtras().getInt("satellites") : 0;
            if (satellites > 0)
                text += satellites;

            mStatusSource.setText(text);
            mStatusSource.setCompoundDrawablesWithIntrinsicBounds(
                    ContextCompat.getDrawable(getActivity(), R.drawable.ic_location), null, null, null);
        } else {
            mStatusSource.setText("");
            mStatusSource.setCompoundDrawablesWithIntrinsicBounds(
                    ContextCompat.getDrawable(getActivity(), R.drawable.ic_signal_wifi), null, null, null);
        }

        mStatusAccuracy.setText(String.format(Locale.getDefault(), "%.1f %s", location.getAccuracy(),
                getString(R.string.unit_meter)));
        mStatusAltitude.setText(String.format(Locale.getDefault(), "%.1f %s", location.getAltitude(),
                getString(R.string.unit_meter)));
        mStatusSpeed.setText(String.format(Locale.getDefault(), "%.1f %s/%s", location.getSpeed() * 3600 / 1000,
                getString(R.string.unit_kilometer), getString(R.string.unit_hour)));
        mStatusLatitude.setText(formatCoordinate(location.getLatitude(), R.string.latitude_caption_short));
        mStatusLongitude.setText(formatCoordinate(location.getLongitude(), R.string.longitude_caption_short));
    }
}

From source file:org.spontaneous.trackservice.RemoteService.java

/**
 * Some GPS waypoints received are of to low a quality for tracking use. Here we filter those out.
 *
 * @param proposedLocation//from w w  w . j  av  a  2s .  c  o  m
 * @return either the (cleaned) original or null when unacceptable
 */
// TODO: Diese Methode auslagern und auch in StartFragment verwenden
public Location locationFilter(Location proposedLocation) {

    // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
    if (proposedLocation != null
            && (proposedLocation.getLatitude() == 0.0d || proposedLocation.getLongitude() == 0.0d)) {
        Log.w(TAG, "A wrong location was received, 0.0 latitude and 0.0 longitude... ");
        proposedLocation = null;
    }

    // Do not log a waypoint which is more inaccurate then is configured to be acceptable
    if (proposedLocation != null && proposedLocation.getAccuracy() > this.mMaxAcceptableAccuracy) {
        Log.w(TAG, String.format("A weak location was received, lots of inaccuracy... (%f is more then max %f)",
                proposedLocation.getAccuracy(), this.mMaxAcceptableAccuracy));
        proposedLocation = addBadLocation(proposedLocation);
    }

    // Do not log a waypoint which might be on any side of the previous waypoint
    if (proposedLocation != null && this.mPreviousLocation != null
            && proposedLocation.getAccuracy() > this.mPreviousLocation.distanceTo(proposedLocation)) {
        Log.w(TAG, String.format(
                "A weak location was received, not quite clear from the previous waypoint... (%f more then max %f)",
                proposedLocation.getAccuracy(), this.mPreviousLocation.distanceTo(proposedLocation)));
        proposedLocation = addBadLocation(proposedLocation);
    }

    // Speed checks, check if the proposed location could be reached from the previous one in sane speed
    // Common to jump on network logging and sometimes jumps on Samsung Galaxy S type of devices
    if (this.mSpeedSanityCheck && proposedLocation != null && this.mPreviousLocation != null) {
        // To avoid near instant teleportation on network location or glitches cause continent hopping
        float meters = proposedLocation.distanceTo(this.mPreviousLocation);
        long seconds = (proposedLocation.getTime() - this.mPreviousLocation.getTime()) / 1000L;
        float speed = meters / seconds;
        if (speed > MAX_REASONABLE_SPEED) {
            Log.w(TAG,
                    "A strange location was received, a really high speed of " + speed + " m/s, prob wrong...");
            proposedLocation = addBadLocation(proposedLocation);
            // Might be a messed up Samsung Galaxy S GPS, reset the logging
            if (speed > 2 * MAX_REASONABLE_SPEED
                    && this.mPrecision != TrackingServiceConstants.LOGGING_GLOBAL) {
                Log.w(TAG, "A strange location was received on GPS, reset the GPS listeners");
                stopListening();
                // mLocationManager.removeGpsStatusListener(mStatusListener);
                this.mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // sendRequestStatusUpdateMessage();
                // sendRequestLocationUpdatesMessage();
            }
        }
    }

    // Remove speed if not sane
    if (this.mSpeedSanityCheck && proposedLocation != null
            && proposedLocation.getSpeed() > MAX_REASONABLE_SPEED) {
        Log.w(TAG, "A strange speed, a really high speed, prob wrong...");
        proposedLocation.removeSpeed();
    }

    // Remove altitude if not sane
    if (this.mSpeedSanityCheck && proposedLocation != null && proposedLocation.hasAltitude()) {
        if (!addSaneAltitude(proposedLocation.getAltitude())) {
            Log.w(TAG, "A strange altitude, a really big difference, prob wrong...");
            proposedLocation.removeAltitude();
        }
    }
    // Older bad locations will not be needed
    if (proposedLocation != null) {
        this.mWeakLocations.clear();
    }
    return proposedLocation;
}

From source file:org.restcomm.app.qoslib.Services.Events.EventUploader.java

/**
 * Uses the provided event instance to generate a {@link EventData} instance.
 * @param _event/*from   w  w  w. j a  v a  2s .c  om*/
 * @return
 */

private EventData generateEventDataFromEvent(EventObj _event, boolean local) {
    Cursor cellDataCursor = null;
    Cursor locationDataCursor = null;
    Cursor signalDataCursor = null;
    boolean bTroubleTweet = false;
    if (_event.getEventType().getIntValue() >= EventType.TT_DROP.getIntValue()
            && _event.getEventType().getIntValue() <= EventType.TT_NO_SVC.getIntValue())
        bTroubleTweet = true;

    try {
        if (!bTroubleTweet) {
            String accuracyWhere = "";
            if (_event.getEventType() == EventType.MAN_PLOTTING
                    || (_event.getFlags() & EventObj.MANUAL_SAMPLES) > 0) {
                accuracyWhere = " and accuracy = -1 or accuracy = -2";
            } else if (_event.getEventType() == EventType.MAN_TRANSIT) {
                accuracyWhere = " and accuracy = -3 or accuracy = -4";
            } else {
                accuracyWhere = " and accuracy <> -1";
            }
            cellDataCursor = getCellsAssociatedWithEvent(_event);
            locationDataCursor = getLocationsAssociatedWithEvent(_event, accuracyWhere);
            signalDataCursor = getSignalStrengthsAssociatedWithEvent(_event);
        }

        int MCCMNC[] = owner.getMCCMNC();
        int mcc = 0;
        int mnc = 0;
        if (MCCMNC != null && MCCMNC.length > 1) {
            mcc = MCCMNC[0];
            mnc = MCCMNC[1];
        }

        int localId = 0;
        if (_event.getUri() != null)
            localId = Integer.parseInt(_event.getUri().getLastPathSegment());

        //if(owner.getLastMMCSignal() != null) {
        //   Integer signal = owner.getLastMMCSignal().getDbmValue(owner.getNetworkType(), owner.getPhoneType());
        //Marking the rssi unknown with -256
        //   rssi = signal != null ? (int)signal : -256;
        //}

        CoverageSamplesSend covSamples = null;
        String neighbors = "";
        String connections = "";
        String trend2 = "";
        String Stats = "";
        String APs = "";
        String Apps = "";
        String ThroughputStats = "";
        String latency = "fail";
        long lookupid1 = 0;
        long lookupid2 = 0;
        String transitAccel = "";

        boolean check = false;

        if (local == false && !bTroubleTweet) {
            try {
                covSamples = trendStringGenerator.generateSamples( //trend string (primary)
                        cellDataCursor, locationDataCursor, signalDataCursor, owner, _event);
            } catch (Exception e) {
                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "generateEventDataFromEvent",
                        "exception occured trying to generate trend string ", e);
            }

            if (locationDataCursor == null || locationDataCursor.getCount() == 0) {
                // failed to get GPS location, send a little GPS diagnosis
                boolean gpsEnabled = owner.getGpsManager().isLocationEnabled();
                if (!gpsEnabled)
                    trend2 = "GPS=disabled,";
                else
                    trend2 = "GPS=enabled,";
            }
            if (_event.getEventType() == EventType.COV_UPDATE) {

                {
                    int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                            .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
                    if (intervalDM > 0) // if enabled
                    {
                        int sleepHandoffs = owner.getUsageLimits().handleCheckin(true);
                        trend2 += "IdleHandoffs=" + sleepHandoffs + ",";
                        SharedPreferences preferenceSettings = PreferenceManager
                                .getDefaultSharedPreferences(owner);
                        int allowDM = preferenceSettings.getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR,
                                0);
                        if (allowDM > 0) {
                            //DataMonitorDBReader dbReader = new DataMonitorDBReader();
                            //DataMonitorDBWriter dbWriter = new DataMonitorDBWriter();

                            try {

                                //get Stats, APs, and Apps strings
                                Stats = "[" + owner.getDataMonitorStats().getStatsString() + "]";
                                APs = "5,type,start,dur,id,sig," + owner.getAccessPointHistory().toString();
                            } catch (Exception e) {
                                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "generateEventDataFromEvent",
                                        "exception in getStatsString: ", e);
                            }
                            try {
                                owner.getAccessPointHistory().clearAccessPointsHistory();
                            } catch (Exception e) {
                                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "generateEventDataFromEvent",
                                        "exception in clearAccessPointsHistory: ", e);
                            }
                            try {
                                Apps = owner.getDataMonitorStats().getRunningAppsString(true);
                                //cleanup
                                owner.getDataMonitorStats().cleanupStatsDB();

                            } catch (Exception e) {
                                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "generateEventDataFromEvent",
                                        "exception in getRunningAppsString: ", e);
                            }

                        }
                    }
                }
            }
            if (_event.getEventType() == EventType.MAN_TRANSIT) {

                lookupid1 = _event.getLookupid1();
                lookupid2 = _event.getLookupid2();
                Apps = _event.getAppData();
                if (lookupid1 == 0 || lookupid2 == 0)
                    return null;
            }
            if (_event.getEventType() == EventType.EVT_VQ_CALL) {
                //Apps = _event.getAppData();
            }
            if (_event.getJSONResult() != null) {
                _event.setTcpStatsToJSON();
                Stats = _event.getJSONResult();
            }

            lookupid2 = _event.getLookupid2();
            lookupid1 = _event.getLookupid1();

            long startTimestamp = _event.getEventTimestamp() - _event.getEventType().getPreEventStageTime(); //get the starting timestamp of the trend string

            neighbors = owner.getCellHistory().getNeighborHistory(startTimestamp, _event.getEventTimestamp());
            connections = owner.getConnectionHistory().getHistory(startTimestamp, _event.getEventTimestamp(),
                    _event.getStageTimestamp() + 5000, _event);
            String servicemode = owner.getConnectionHistory().getServiceModeHistory(startTimestamp,
                    _event.getEventTimestamp(), _event.getStageTimestamp() + 5000, _event.getEventType());
            if (servicemode != null && servicemode.length() > 10)
                trend2 = servicemode;
        }

        String apiKey = MainService.getApiKey(owner);

        int iUserID = MainService.getUserID(owner);
        if (iUserID == 0)
            iUserID = -1;
        Location location = _event.getLocation();

        if (location == null) {
            location = new Location("");
            if (_event.getEventType() == EventType.MAN_TRANSIT) {
                String loc = PreferenceManager.getDefaultSharedPreferences(owner).getString("transitEvent",
                        null);
                if (loc != null) {
                    String[] locs = loc.split(",");
                    int lat = Integer.valueOf(locs[0]);
                    int lon = Integer.valueOf(locs[1]);
                    location = new Location("");
                    location.setLatitude(lat / 1000000.0);
                    location.setLongitude(lon / 1000000.0);
                    PreferenceManager.getDefaultSharedPreferences(owner).edit().putString("transitEvent", null)
                            .commit();
                }
            }
        }

        int bsHigh = 0, bsLow = 0, bsMid = 0, bsCode = 0;

        if (_event.getCell() != null) {
            bsHigh = _event.getCell().getBSHigh();
            bsLow = _event.getCell().getBSLow();
            bsMid = _event.getCell().getBSMid();
            bsCode = _event.getCell().getBSCode();
        }

        Integer signalDB = -255;
        if (_event.getSignal() != null)
            signalDB = _event.getSignal().getDbmValue(owner.getPhoneState().getNetworkType(),
                    owner.getPhoneState().getPhoneType());
        // unknown signal? server sees that as -255
        if (signalDB == null || signalDB == 0)
            signalDB = -255;

        EventData eventData = new EventData(0, // 1 would allow the server to request an auto speed test
                _event.getConnectTime(), //ConnectTime
                "", //phone number
                owner.getPhoneState().getNetworkOperatorName(),
                String.format("Android %s,%s,%s", DeviceInfoOld.getManufacturer(),
                        DeviceInfoOld.getPhoneModel(), DeviceInfoOld.getDevice()),
                _event.getDuration(), // the duration between the event and last complementary event
                covSamples, // trend string 
                trend2, //trend string (secondary)
                neighbors, connections, _event.getEventTimestamp() / 1000, location.getTime() / 1000, //timestamp of the gps fix used for this event (will be filled later)
                0L, //lStartTime (will be filled later)
                (float) location.getLongitude(), //fltEventLng is the unscaled latitude
                (float) location.getLatitude(), //fltEventLat is the unscaled longitude
                _event.getEventType().getIntValue(), _event.getEventID(), //we don't know the server side event id yet
                0L, //This is generated by the server so we don't worry about it just yet
                (int) _event.getEventIndex(), 0, //sample interval is deprecated
                (int) location.getAltitude(), //altitude (will be filled later)
                (int) location.getAccuracy(), //uncertainty (will be filled later)
                (int) location.getSpeed(), //speed (will be filled later)
                (int) location.getBearing(), //heading (will be filled later)
                _event.getSatellites(), //number of satellites
                signalDB, //signal strengh (will be filled later)
                bsLow, // cellId at the time of the event
                bsMid, //nid
                bsCode, //previous cell (will be filled later) 
                getAppVersionCode(), _event.getBattery(), // battery level
                0, // ec/i0 may be filled in later
                _event.getFlags(), // flags
                localId, //CallId is internal to the server
                iUserID, mcc, mnc, bsHigh, //LAC 
                _event.getCause(), // cause of dropped call
                apiKey, DeviceInfo.getIPAddress(), Stats, APs, Apps, latency, lookupid1, lookupid2);

        eventData.setAppName(_event.getAppName());
        if (_event.getEventType().waitsForSpeed()) {
            eventData.setLatency(_event.getLatency());
            eventData.setDownloadSpeed(_event.getDownloadSpeed());
            eventData.setUploadSpeed(_event.getUploadSpeed());
            eventData.setDownloadSize(_event.getDownloadSize());
            eventData.setUploadSize(_event.getUploadSize());
            eventData.setTier(_event.getTier());
            if (_event.getEventType() == EventType.LATENCY_TEST && _event.getLatency() < 0)
                eventData.setDownloadSpeed(-_event.getLatency());

        }

        if (_event.getEventType() == EventType.APP_MONITORING && !local) {

            if (_event.getAppData() != null) {
                eventData.setRunningApps(_event.getAppData());
                LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "generateEventDataFromEvent",
                        "AppData: " + _event.getAppData());
            }

        }

        if (_event.getEventID() > 0)
            eventData.setEventId(_event.getEventID());
        eventData.setWifi(_event.getWifiInfo(), _event.getWifiConfig());

        return eventData;
    } catch (Exception ex) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "generateEventDataFromEvent",
                "exception occured trying to generate event data ", ex);
    } finally {
        //now close the cursors
        if (cellDataCursor != null)
            cellDataCursor.close();
        if (locationDataCursor != null)
            locationDataCursor.close();
        if (signalDataCursor != null)
            signalDataCursor.close();
    }
    return null;
}

From source file:org.dicadeveloper.runnerapp.services.TrackRecordingService.java

/**
 * Called when location changed./*from w w  w  .  ja  v a  2  s .  c om*/
 * 
 * @param location the location
 */
private void onLocationChangedAsync(Location location) {
    try {
        if (!isRecording() || isPaused()) {
            Log.w(TAG, "Ignore onLocationChangedAsync. Not recording or paused.");
            return;
        }

        Track track = myTracksProviderUtils.getTrack(recordingTrackId);
        if (track == null) {
            Log.w(TAG, "Ignore onLocationChangedAsync. No track.");
            return;
        }

        if (!LocationUtils.isValidLocation(location)) {
            Log.w(TAG, "Ignore onLocationChangedAsync. location is invalid.");
            return;
        }

        if (!location.hasAccuracy() || location.getAccuracy() >= recordingGpsAccuracy) {
            Log.d(TAG, "Ignore onLocationChangedAsync. Poor accuracy.");
            return;
        }

        // Fix for phones that do not set the time field
        if (location.getTime() == 0L) {
            location.setTime(System.currentTimeMillis());
        }

        Location lastValidTrackPoint = getLastValidTrackPointInCurrentSegment(track.getId());
        long idleTime = 0L;
        if (lastValidTrackPoint != null && location.getTime() > lastValidTrackPoint.getTime()) {
            idleTime = location.getTime() - lastValidTrackPoint.getTime();
        }
        locationListenerPolicy.updateIdleTime(idleTime);
        if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) {
            registerLocationListener();
        }

        SensorDataSet sensorDataSet = getSensorDataSet();
        if (sensorDataSet != null) {
            location = new MyTracksLocation(location, sensorDataSet);
        }

        // Always insert the first segment location
        if (!currentSegmentHasLocation) {
            insertLocation(track, location, null);
            currentSegmentHasLocation = true;
            lastLocation = location;
            return;
        }

        if (!LocationUtils.isValidLocation(lastValidTrackPoint)) {
            /*
             * Should not happen. The current segment should have a location. Just
             * insert the current location.
             */
            insertLocation(track, location, null);
            lastLocation = location;
            return;
        }

        double distanceToLastTrackLocation = location.distanceTo(lastValidTrackPoint);
        if (distanceToLastTrackLocation > maxRecordingDistance) {
            insertLocation(track, lastLocation, lastValidTrackPoint);

            Location pause = new Location(LocationManager.GPS_PROVIDER);
            pause.setLongitude(0);
            pause.setLatitude(PAUSE_LATITUDE);
            pause.setTime(lastLocation.getTime());
            insertLocation(track, pause, null);

            insertLocation(track, location, null);
            isIdle = false;
        } else if (sensorDataSet != null || distanceToLastTrackLocation >= recordingDistanceInterval) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = false;
        } else if (!isIdle && location.hasSpeed() && location.getSpeed() < MAX_NO_MOVEMENT_SPEED) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = true;
        } else if (isIdle && location.hasSpeed() && location.getSpeed() >= MAX_NO_MOVEMENT_SPEED) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = false;
        } else {
            Log.d(TAG, "Not recording location, idle");
        }
        lastLocation = location;
    } catch (Error e) {
        Log.e(TAG, "Error in onLocationChangedAsync", e);
        throw e;
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in onLocationChangedAsync", e);
        throw e;
    }
}

From source file:br.com.bioscada.apps.biotracks.services.TrackRecordingService.java

/**
 * Called when location changed./*from w  ww .  ja v  a2  s  . co  m*/
 *
 * @param location the location
 */
private void onLocationChangedAsync(Location location) {
    try {
        if (!isRecording() || isPaused()) {
            Log.w(TAG, "Ignore onLocationChangedAsync. Not recording or paused.");
            return;
        }

        Track track = myTracksProviderUtils.getTrack(recordingTrackId);
        if (track == null) {
            Log.w(TAG, "Ignore onLocationChangedAsync. No track.");
            return;
        }

        if (!LocationUtils.isValidLocation(location)) {
            Log.w(TAG, "Ignore onLocationChangedAsync. location is invalid.");
            return;
        }

        if (!location.hasAccuracy() || location.getAccuracy() >= recordingGpsAccuracy) {
            Log.d(TAG, "Ignore onLocationChangedAsync. Poor accuracy.");
            return;
        }

        // Fix for phones that do not set the time field
        if (location.getTime() == 0L) {
            location.setTime(System.currentTimeMillis());
        }

        Location lastValidTrackPoint = getLastValidTrackPointInCurrentSegment(track.getId());
        long idleTime = 0L;
        if (lastValidTrackPoint != null && location.getTime() > lastValidTrackPoint.getTime()) {
            idleTime = location.getTime() - lastValidTrackPoint.getTime();
        }
        locationListenerPolicy.updateIdleTime(idleTime);
        if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) {
            registerLocationListener();
        }

        Sensor.SensorDataSet sensorDataSet = getSensorDataSet();
        if (sensorDataSet != null) {
            location = new MyTracksLocation(location, sensorDataSet);
        }

        // Always insert the first segment location
        if (!currentSegmentHasLocation) {
            insertLocation(track, location, null);
            currentSegmentHasLocation = true;
            lastLocation = location;
            return;
        }

        if (!LocationUtils.isValidLocation(lastValidTrackPoint)) {
            /*
             * Should not happen. The current segment should have a location. Just
             * insert the current location.
             */
            insertLocation(track, location, null);
            lastLocation = location;
            return;
        }

        double distanceToLastTrackLocation = location.distanceTo(lastValidTrackPoint);
        if (distanceToLastTrackLocation > maxRecordingDistance) {
            insertLocation(track, lastLocation, lastValidTrackPoint);

            Location pause = new Location(LocationManager.GPS_PROVIDER);
            pause.setLongitude(0);
            pause.setLatitude(PAUSE_LATITUDE);
            pause.setTime(lastLocation.getTime());
            insertLocation(track, pause, null);

            insertLocation(track, location, null);
            isIdle = false;
        } else if (sensorDataSet != null || distanceToLastTrackLocation >= recordingDistanceInterval) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = false;
        } else if (!isIdle && location.hasSpeed() && location.getSpeed() < MAX_NO_MOVEMENT_SPEED) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = true;
        } else if (isIdle && location.hasSpeed() && location.getSpeed() >= MAX_NO_MOVEMENT_SPEED) {
            insertLocation(track, lastLocation, lastValidTrackPoint);
            insertLocation(track, location, null);
            isIdle = false;
        } else {
            Log.d(TAG, "Not recording location, idle");
        }
        lastLocation = location;
    } catch (Error e) {
        Log.e(TAG, "Error in onLocationChangedAsync", e);
        throw e;
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in onLocationChangedAsync", e);
        throw e;
    }
}

From source file:com.vonglasow.michael.satstat.ui.GpsSectionFragment.java

/**
 * Called by {@link MainActivity} when a new location is found by the GPS location provider.
 * Stores the location and updates GPS display and map view.
 *///from  w w  w .  j  a  v a2  s .  co m
public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
        Float getAcc = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAcc = (float) (location.getAccuracy());
        } else {
            getAcc = (float) (location.getAccuracy() * (float) 3.28084);
        }
        gpsAccuracy.setText(String.format("%.0f", getAcc));
        gpsAccuracyUnit
                .setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
    } else {
        gpsAccuracy.setText(getString(R.string.value_none));
        gpsAccuracyUnit.setText("");
    }

    if (mainActivity.prefCoord == Const.KEY_PREF_COORD_DECIMAL) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_MIN) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double min = 60.0 * (dec - deg);
        gpsLat.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
        dec = location.getLongitude();
        deg = (int) dec;
        min = 60.0 * (dec - deg);
        gpsLon.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_SEC) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double tmp = 60.0 * (dec - deg);
        double min = (int) tmp;
        double sec = 60.0 * (tmp - min);
        gpsLat.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
        dec = location.getLongitude();
        deg = (int) dec;
        tmp = 60.0 * (dec - deg);
        min = (int) tmp;
        sec = 60.0 * (tmp - min);
        gpsLon.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_MGRS) {
        gpsLatLayout.setVisibility(View.GONE);
        gpsLonLayout.setVisibility(View.GONE);
        gpsCoordLayout.setVisibility(View.VISIBLE);
        gpsCoord.setText(new LatLng(location.getLatitude(), location.getLongitude()).toMGRSRef()
                .toString(MGRSRef.PRECISION_1M));
    }
    if (mainActivity.prefUtc)
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    else
        df.setTimeZone(TimeZone.getDefault());
    gpsTime.setText(df.format(new Date(location.getTime())));

    if (location.hasAltitude()) {
        Float getAltitude = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAltitude = (float) (location.getAltitude());
        } else {
            getAltitude = (float) (location.getAltitude() * (float) 3.28084);
        }
        gpsAlt.setText(String.format("%.0f", getAltitude));
        gpsAltUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
        orDeclination.setText(String.format("%.0f%s",
                new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                        (float) (getAltitude), location.getTime()).getDeclination(),
                getString(R.string.unit_degree)));
    } else {
        gpsAlt.setText(getString(R.string.value_none));
        gpsAltUnit.setText("");
        orDeclination.setText(getString(R.string.value_none));
    }

    if (location.hasBearing()) {
        gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
        gpsOrientation.setText(MainActivity.formatOrientation(this.getContext(), location.getBearing()));
    } else {
        gpsBearing.setText(getString(R.string.value_none));
        gpsOrientation.setText(getString(R.string.value_none));
    }

    if (location.hasSpeed()) {
        Float getSpeed = (float) 0.0;
        if (mainActivity.prefKnots) {
            getSpeed = (float) (location.getSpeed() * 1.943844f);
        } else if (mainActivity.prefUnitType) {
            getSpeed = (float) (location.getSpeed() * 3.6f);
        } else {
            getSpeed = (float) (location.getSpeed() * 2.23694f);
        }
        gpsSpeed.setText(String.format("%.0f", getSpeed));
        gpsSpeedUnit.setText(getString(((mainActivity.prefKnots) ? R.string.unit_kn
                : (mainActivity.prefUnitType) ? R.string.unit_km_h : R.string.unit_mph)));
    } else {
        gpsSpeed.setText(getString(R.string.value_none));
        gpsSpeedUnit.setText("");
    }

    // note: getting number of sats in fix by looking for "satellites"
    // in location's extras doesn't seem to work, always returns 0 sats
}

From source file:com.vonglasow.michael.satstat.GpsSectionFragment.java

/**
 * Called by {@link MainActivity} when a new location is found by the GPS location provider.
 * Stores the location and updates GPS display and map view.
 *///from   w w  w  .j  a va2s . c o m
public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
        Float getAcc = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAcc = (float) (location.getAccuracy());
        } else {
            getAcc = (float) (location.getAccuracy() * (float) 3.28084);
        }
        gpsAccuracy.setText(String.format("%.0f", getAcc));
        gpsAccuracyUnit
                .setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
    } else {
        gpsAccuracy.setText(getString(R.string.value_none));
        gpsAccuracyUnit.setText("");
    }

    if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_DECIMAL) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MIN) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double min = 60.0 * (dec - deg);
        gpsLat.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
        dec = location.getLongitude();
        deg = (int) dec;
        min = 60.0 * (dec - deg);
        gpsLon.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_SEC) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double tmp = 60.0 * (dec - deg);
        double min = (int) tmp;
        double sec = 60.0 * (tmp - min);
        gpsLat.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
        dec = location.getLongitude();
        deg = (int) dec;
        tmp = 60.0 * (dec - deg);
        min = (int) tmp;
        sec = 60.0 * (tmp - min);
        gpsLon.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MGRS) {
        gpsLatLayout.setVisibility(View.GONE);
        gpsLonLayout.setVisibility(View.GONE);
        gpsCoordLayout.setVisibility(View.VISIBLE);
        gpsCoord.setText(new LatLng(location.getLatitude(), location.getLongitude()).toMGRSRef()
                .toString(MGRSRef.PRECISION_1M));
    }
    if (mainActivity.prefUtc)
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    else
        df.setTimeZone(TimeZone.getDefault());
    gpsTime.setText(df.format(new Date(location.getTime())));

    if (location.hasAltitude()) {
        Float getAltitude = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAltitude = (float) (location.getAltitude());
        } else {
            getAltitude = (float) (location.getAltitude() * (float) 3.28084);
        }
        gpsAlt.setText(String.format("%.0f", getAltitude));
        gpsAltUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
        orDeclination.setText(String.format("%.0f%s",
                new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                        (float) (getAltitude), location.getTime()).getDeclination(),
                getString(R.string.unit_degree)));
    } else {
        gpsAlt.setText(getString(R.string.value_none));
        gpsAltUnit.setText("");
        orDeclination.setText(getString(R.string.value_none));
    }

    if (location.hasBearing()) {
        gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
        gpsOrientation.setText(MainActivity.formatOrientation(this.getContext(), location.getBearing()));
    } else {
        gpsBearing.setText(getString(R.string.value_none));
        gpsOrientation.setText(getString(R.string.value_none));
    }

    if (location.hasSpeed()) {
        Float getSpeed = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getSpeed = (float) (location.getSpeed() * 3.6f);
        } else {
            getSpeed = (float) (location.getSpeed() * 3.6f * 2.23694f);
        }
        gpsSpeed.setText(String.format("%.0f", getSpeed));
        gpsSpeedUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_km_h : R.string.unit_mph)));
    } else {
        gpsSpeed.setText(getString(R.string.value_none));
        gpsSpeedUnit.setText("");
    }

    // note: getting number of sats in fix by looking for "satellites"
    // in location's extras doesn't seem to work, always returns 0 sats
}

From source file:com.example.sensingapp.SensingApp.java

public void recordSensingInfo(SensorData senData) {
    String sRecordLine;//from  ww w. ja v a  2 s. c  o m
    String sTimeField;
    Date dtCurDate;
    int i;
    long lStartTime = 0;
    long lCurrentTime = 0;
    SimpleDateFormat spdRecordTime, spdCurDateTime;
    final String DATE_FORMAT = "yyyyMMddHHmmss";
    final String DATE_FORMAT_S = "yyMMddHHmmssSSS"; //"yyyyMMddHHmmssSSS"
    int nSensorReadingType = SENSOR_EVENT_NULL;
    int nSensorDataType;

    if (m_blnRecordStatus == false) { //Stopped
        return;
    }

    dtCurDate = new Date();

    // Timestamp for the record
    spdRecordTime = new SimpleDateFormat(DATE_FORMAT_S);
    sTimeField = spdRecordTime.format(dtCurDate);

    nSensorDataType = senData.getSensorDataType();

    if (nSensorDataType == DATA_TYPE_SENSOR) {
        SensorEvent event;

        event = senData.getSensorEvent();

        synchronized (this) {
            switch (event.sensor.getType()) {

            case Sensor.TYPE_ACCELEROMETER:
                //X, Y, Z
                if (m_blnAcclEnabled) {
                    m_sAccl = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + ","
                            + Float.toString(event.values[2]) + ",";

                    nSensorReadingType = SENSOR_EVENT_ACCL;
                }

                //                   if (m_blnOrientEnabled) {
                //                      m_arrfAcclValues = event.values.clone();
                //                      
                //                      if (calculateOrientation()) {
                //                         //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis)
                //                         m_sOrient = Float.toString(m_arrfOrientValues[0]) + "," + 
                //                                  Float.toString(m_arrfOrientValues[1]) + "," + 
                //                                  Float.toString(m_arrfOrientValues[2]) + ",";
                //                         
                //                         nSensorReadingType = SENSOR_EVENT_ORIENT;
                //                         
                //                      }
                //                   }
                break;

            case Sensor.TYPE_LINEAR_ACCELERATION:
                //X,Y,Z
                if (m_blnLinearAcclEnabled) {
                    m_sLinearAccl = Float.toString(event.values[0]) + "," + Float.toString(event.values[1])
                            + "," + Float.toString(event.values[2]) + ",";

                    nSensorReadingType = SENSOR_EVENT_LINEAR_ACCL;
                }

                break;

            case Sensor.TYPE_GRAVITY:
                //X,Y,Z
                if (m_blnGravityEnabled) {
                    m_sGravity = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + ","
                            + Float.toString(event.values[2]) + ",";

                    nSensorReadingType = SENSOR_EVENT_GRAVITY;
                }

                break;

            case Sensor.TYPE_GYROSCOPE:
                //X,Y,Z
                m_sGyro = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + ","
                        + Float.toString(event.values[2]) + ",";
                nSensorReadingType = SENSOR_EVENT_GYRO;
                break;

            case Sensor.TYPE_MAGNETIC_FIELD:
                // Values are in micro-Tesla (uT) and measure the ambient magnetic field 
                if (m_blnMagnetEnabled) {
                    m_sMagnet = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + ","
                            + Float.toString(event.values[2]) + ",";

                    nSensorReadingType = SENSOR_EVENT_MAGNET;
                }

                //                   if (m_blnOrientEnabled) {
                //                      m_arrfMagnetValues = event.values.clone();
                //                      
                //                      if (calculateOrientation()) {
                //                         //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis)
                //                         m_sOrient = Float.toString(m_arrfOrientValues[0]) + "," + 
                //                                  Float.toString(m_arrfOrientValues[1]) + "," + 
                //                                  Float.toString(m_arrfOrientValues[2]) + ",";
                //                                                  
                //                         if (nSensorReadingType != SENSOR_EVENT_MAGNET) {
                //                            nSensorReadingType = SENSOR_EVENT_ORIENT;
                //                         }
                //                      }
                //                   }

                break;

            case Sensor.TYPE_ROTATION_VECTOR: //Added on 20150910
                if (m_blnOrientEnabled) {
                    float[] arrfRotVal = new float[3];
                    float[] arrfR = new float[9];
                    float[] arrfValues = new float[3];

                    try {
                        System.arraycopy(event.values, 0, arrfRotVal, 0, event.values.length);
                    } catch (IllegalArgumentException e) {
                        //Hardcode the size to handle a bug on Samsung devices
                        System.arraycopy(event.values, 0, arrfRotVal, 0, 3);
                    }

                    SensorManager.getRotationMatrixFromVector(arrfR, arrfRotVal);
                    SensorManager.getOrientation(arrfR, arrfValues);

                    m_arrfOrientValues[0] = (float) Math.toDegrees(arrfValues[0]);
                    m_arrfOrientValues[1] = (float) Math.toDegrees(arrfValues[1]);
                    m_arrfOrientValues[2] = (float) Math.toDegrees(arrfValues[2]);

                    if (m_arrfOrientValues[0] < 0) {
                        m_arrfOrientValues[0] = m_arrfOrientValues[0] + 360; // Make Azimuth 0 ~ 360
                    }

                    //                      //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis)
                    m_sOrient = Float.toString(m_arrfOrientValues[0]) + ","
                            + Float.toString(m_arrfOrientValues[1]) + ","
                            + Float.toString(m_arrfOrientValues[2]) + ",";

                    //m_tvGpsUp.setText(m_sOrient); //Show orientation
                    nSensorReadingType = SENSOR_EVENT_ORIENT;
                }

                break;

            case Sensor.TYPE_LIGHT:
                // Ambient light level in SI lux units 
                m_sLight = Float.toString(event.values[0]) + ",";
                nSensorReadingType = SENSOR_EVENT_LIGHT;
                break;

            case Sensor.TYPE_PRESSURE:
                // Atmospheric pressure in hPa (millibar)
                m_sBarometer = Float.toString(event.values[0]) + ",";
                nSensorReadingType = SENSOR_EVENT_BAROMETER;
                break;

            }
        }
    } else if (nSensorDataType == DATA_TYPE_GPS) {
        Location locationGps;
        locationGps = senData.getGpsLocation();

        if (locationGps != null) {

            m_location = new Location(locationGps);

            //Change from double to float
            m_sGPS = Float.valueOf((float) (locationGps.getLatitude())).toString() + ","
                    + Float.valueOf((float) (locationGps.getLongitude())).toString() + ",";
            if (locationGps.hasAltitude()) {
                m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getAltitude())).toString() + ",";
                GeomagneticField geoField = new GeomagneticField(
                        Double.valueOf(locationGps.getLatitude()).floatValue(),
                        Double.valueOf(locationGps.getLongitude()).floatValue(),
                        Double.valueOf(locationGps.getAltitude()).floatValue(), System.currentTimeMillis());
                // Append Declination, in Degree
                m_sGPS = m_sGPS + Float.valueOf((float) (geoField.getDeclination())).toString() + ","
                        + Float.valueOf((float) (geoField.getInclination())).toString() + ",";
            } else {
                m_sGPS = m_sGPS + ",,,";
                //m_sGPS = m_sGPS + ",";
            }

            //New add 201408270009
            if (locationGps.hasSpeed()) {
                m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getSpeed())).toString() + ",";
            } else {
                m_sGPS = m_sGPS + ",";
            }

            if (locationGps.hasBearing()) {
                m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getBearing())).toString() + ",";
            } else {
                m_sGPS = m_sGPS + ",";
            }

            nSensorReadingType = SENSOR_EVENT_GPS;

            m_blnGpsUp = true;
            show_screen5_GpsUp();
        } else {
            m_blnGpsUp = false;
            show_screen5_GpsUp();
        }
    } else if (nSensorDataType == DATA_TYPE_MIC) {
        double fSoundLevelDb;
        fSoundLevelDb = senData.getSoundLevelDb();
        m_sSouldLevel = new BigDecimal(fSoundLevelDb).setScale(0, BigDecimal.ROUND_HALF_UP) + ",";

        nSensorReadingType = SENSOR_EVENT_MIC;

    } else if (nSensorDataType == DATA_TYPE_CELLULAR) {
        int nCellId;
        nCellId = senData.getCellId();
        m_sCellId = Integer.valueOf(nCellId).toString() + ",";
        nSensorReadingType = SENSOR_EVENT_CELLULAR;

    } else if (nSensorDataType == DATA_TYPE_WIFI) {
        List<WifiData> lstWifiData = senData.getListWifiData();
        int nWifiCnt = Math.min(WIFI_COUNT, lstWifiData.size());
        m_sWifi = "";
        for (i = 0; i < nWifiCnt; i++) {
            //m_sWifi = m_sWifi + lstWifiData.get(i).getSSID() + "," + lstWifiData.get(i).getBSSID() + "," + lstWifiData.get(i).getSignalLevel() + ",";
            m_sWifi = m_sWifi + lstWifiData.get(i).getBSSID() + "," + lstWifiData.get(i).getSignalLevel() + ",";

        }

        for (i = 1; i <= WIFI_COUNT - nWifiCnt; i++) {
            //m_sWifi = m_sWifi + ",,,";
            m_sWifi = m_sWifi + ",,";
        }

        nSensorReadingType = SENSOR_EVENT_WIFI;
    }

    if (nSensorReadingType == SENSOR_EVENT_NULL) {
        return;
    }

    sRecordLine = sTimeField + ",";

    if (m_blnNoLabel == false) {
        sRecordLine = sRecordLine + m_sCurrentLabel + ",";
    }

    sRecordLine = sRecordLine + Integer.valueOf(nSensorReadingType) + ",";

    //New: Every field always there
    //Field in each line:
    /*
     *  1) Timestamp
     *  2) Label
     *  3) SensingEventType
     *  4-6) Accl
     *  7-9) Linear Accl
     *  10-12) Gravity
     *  13-15) Gyro
     *  16-18) Orientation
     *  19-21) Magnet
     *  22) Light
     *  23) Barometer
     *  24) Sould Level (Decibel)
     *  25) Cell ID
     *  26-32) GPS (Lat, Long, Alt, Declination, Inclination, Speed, Bearing)
     *  33-72) WiFi (<BSSID, Level>) 
     */
    //      sRecordLine = sRecordLine  + m_sAccl + m_sGyro + m_sOrient + m_sMagnet + 
    //                           m_sLight + m_sBarometer +  
    //                           m_sSouldLevel + m_sCellId +
    //                           m_sGPS + m_sWifi;

    sRecordLine = sRecordLine + m_sAccl + m_sLinearAccl + m_sGravity + m_sGyro + m_sOrient + m_sMagnet
            + m_sLight + m_sBarometer + m_sSouldLevel + m_sCellId + m_sGPS + m_sWifi;

    ////////////////////////////
    //      String sAngle = calculateRot(m_sAccl, m_sGravity);
    //      String sarrAngle[] = sAngle.split(",");
    //      String sShow = sarrAngle[0] + "\n" + sarrAngle[1];

    //      String sShow = "";

    //      if (m_sGravity.length() > 3) {
    //         String sarrAngle[] = m_sGravity.split(",");
    //         double fX = Double.valueOf(sarrAngle[0]).doubleValue();
    //         double fY = Double.valueOf(sarrAngle[1]).doubleValue();
    //         double fZ = Double.valueOf(sarrAngle[2]).doubleValue();
    //         
    //         double fTotal = Math.sqrt(fX*fX + fY*fY + fZ*fZ);
    //         
    //         double fAngleZ = Math.acos(fZ/fTotal)/Math.PI*180;
    //         double fAngleY = 90 - Math.acos(fY/fTotal)/Math.PI*180;
    //         double fAngleX = 90 - Math.acos(fX/fTotal)/Math.PI*180;
    //         
    //         sShow = "X:  " +  fAngleX + "\n";
    //         sShow = sShow + "Y:  " +  fAngleY + "\n";
    //         sShow = sShow + "Z:  " +  fAngleZ;
    //         
    //                     
    //      }

    //      if (m_sGravity.length() > 3) {
    //         String sarrAngle[] = m_sGravity.split(",");
    //         double fX = Double.valueOf(sarrAngle[0]).doubleValue();
    //         double fY = Double.valueOf(sarrAngle[1]).doubleValue();
    //         double fZ = Double.valueOf(sarrAngle[2]).doubleValue();
    //         
    //         int nSymbol = 0;
    //         if (fX < 0)  {
    //            sShow = sShow + "- X" + "\n";
    //         } else if (fX > 0) {
    //            sShow = sShow + "+ X" + "\n";
    //         }
    //         
    //         if (fY < 0)  {
    //            sShow = sShow + "- Y" + "\n";
    //         } else if (fY > 0) {
    //            sShow = sShow + "+ Y" + "\n";
    //         }
    //         
    //         if (fZ < 0)  {
    //            sShow = sShow + "- Z";
    //         } else if (fZ > 0) {
    //            sShow = sShow + "+ Z";
    //         }
    //                     
    //      }
    //      
    //      if (m_sGyro.length() > 3) {
    //         String sarrAngle[] = m_sGyro.split(",");
    //         double fX = Double.valueOf(sarrAngle[0]).doubleValue();
    //         double fY = Double.valueOf(sarrAngle[1]).doubleValue();
    //         double fZ = Double.valueOf(sarrAngle[2]).doubleValue();
    //         
    //         int nSymbol = 0;
    //         if (fX < 0)  {
    //            nSymbol = -1;
    //         } else if (fX > 0) {
    //            nSymbol = 1;
    //         }
    //         
    //         if (fY < 0)  {
    //            nSymbol = nSymbol + (-1);
    //         } else if (fY > 0) {
    //            nSymbol = nSymbol + 1;
    //         }
    //         
    //         if (fZ < 0)  {
    //            nSymbol = nSymbol + (-1);
    //         } else if (fZ > 0) {
    //            nSymbol = nSymbol + 1;
    //         }
    //            
    //         if (nSymbol < 0) {
    //            nSymbol = -1;
    //         } else if (nSymbol > 0) {
    //            nSymbol = 1;
    //         }
    //         
    //         sShow = sShow + "\n\n" + nSymbol + "";
    //      }

    //      m_tvSensingInfo.setText(sShow);
    ////////////////////////////

    sRecordLine = sRecordLine + System.getProperty("line.separator");

    if (m_fwSensorRecord != null) {
        //Write information into file
        //Compose information into recordLine
        try {
            m_fwSensorRecord.write(sRecordLine);
        } catch (IOException e) {

        }
    }

}

From source file:com.vonglasow.michael.satstat.MainActivity.java

/**
 * Called when a new location is found by a registered location provider.
 * Stores the location and updates GPS display and map view.
 *//*from www  .  ja  v a2 s  .c  om*/
public void onLocationChanged(Location location) {
    // some providers may report NaN for latitude and longitude:
    // if that happens, do not process this location and mark any previous
    // location from that provider as stale
    if (Double.isNaN(location.getLatitude()) || Double.isNaN(location.getLongitude())) {
        markLocationAsStale(providerLocations.get(location.getProvider()));
        if (isMapViewReady)
            applyLocationProviderStyle(this, location.getProvider(), LOCATION_PROVIDER_GRAY);
        return;
    }

    if (providerLocations.containsKey(location.getProvider()))
        providerLocations.put(location.getProvider(), new Location(location));

    // update map view
    if (isMapViewReady) {
        LatLong latLong = new LatLong(location.getLatitude(), location.getLongitude());

        Circle circle = mapCircles.get(location.getProvider());
        Marker marker = mapMarkers.get(location.getProvider());

        if (circle != null) {
            circle.setLatLong(latLong);
            if (location.hasAccuracy()) {
                circle.setVisible(true);
                circle.setRadius(location.getAccuracy());
            } else {
                Log.d("MainActivity", "Location from " + location.getProvider() + " has no accuracy");
                circle.setVisible(false);
            }
        }

        if (marker != null) {
            marker.setLatLong(latLong);
            marker.setVisible(true);
        }

        applyLocationProviderStyle(this, location.getProvider(), null);

        Runnable invalidator = providerInvalidators.get(location.getProvider());
        if (invalidator != null) {
            providerInvalidationHandler.removeCallbacks(invalidator);
            providerInvalidationHandler.postDelayed(invalidator, PROVIDER_EXPIRATION_DELAY);
        }

        // redraw, move locations into view and zoom out as needed
        if ((circle != null) || (marker != null) || (invalidator != null))
            updateMap();
    }

    // update GPS view
    if ((location.getProvider().equals(LocationManager.GPS_PROVIDER)) && (isGpsViewReady)) {
        if (location.hasAccuracy()) {
            gpsAccuracy.setText(String.format("%.0f", location.getAccuracy()));
        } else {
            gpsAccuracy.setText(getString(R.string.value_none));
        }

        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
        gpsTime.setText(String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", location.getTime()));

        if (location.hasAltitude()) {
            gpsAlt.setText(String.format("%.0f", location.getAltitude()));
            orDeclination.setText(String.format("%.0f%s",
                    new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                            (float) location.getAltitude(), location.getTime()).getDeclination(),
                    getString(R.string.unit_degree)));
        } else {
            gpsAlt.setText(getString(R.string.value_none));
            orDeclination.setText(getString(R.string.value_none));
        }

        if (location.hasBearing()) {
            gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
            gpsOrientation.setText(formatOrientation(location.getBearing()));
        } else {
            gpsBearing.setText(getString(R.string.value_none));
            gpsOrientation.setText(getString(R.string.value_none));
        }

        if (location.hasSpeed()) {
            gpsSpeed.setText(String.format("%.0f", (location.getSpeed()) * 3.6));
        } else {
            gpsSpeed.setText(getString(R.string.value_none));
        }

        // note: getting number of sats in fix by looking for "satellites"
        // in location's extras doesn't seem to work, always returns 0 sats
    }
}