Example usage for android.location LocationManager NETWORK_PROVIDER

List of usage examples for android.location LocationManager NETWORK_PROVIDER

Introduction

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

Prototype

String NETWORK_PROVIDER

To view the source code for android.location LocationManager NETWORK_PROVIDER.

Click Source Link

Document

Name of the network location provider.

Usage

From source file:org.egov.android.view.activity.CreateComplaintActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (isCurrentLocation) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
    }//from   w  w w  .  j  a  v  a  2  s . c o  m

}

From source file:org.telegram.ui.ThemeActivity.java

private void updateSunTime(Location lastKnownLocation, boolean forceUpdate) {
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            if (activity.checkSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION }, 2);
                return;
            }//from  w  w  w  .j  a va 2s. c  om
        }
    }
    if (getParentActivity() != null) {
        if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
            return;
        }
        try {
            LocationManager lm = (LocationManager) ApplicationLoader.applicationContext
                    .getSystemService(Context.LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("GpsDisabledAlert", R.string.GpsDisabledAlert));
                builder.setPositiveButton(
                        LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable),
                        (dialog, id) -> {
                            if (getParentActivity() == null) {
                                return;
                            }
                            try {
                                getParentActivity().startActivity(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            } catch (Exception ignore) {

                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
                return;
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    try {
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    if (lastKnownLocation == null || forceUpdate) {
        startLocationUpdate();
        if (lastKnownLocation == null) {
            return;
        }
    }
    Theme.autoNightLocationLatitude = lastKnownLocation.getLatitude();
    Theme.autoNightLocationLongitude = lastKnownLocation.getLongitude();
    int time[] = SunDate.calculateSunriseSunset(Theme.autoNightLocationLatitude,
            Theme.autoNightLocationLongitude);
    Theme.autoNightSunriseTime = time[0];
    Theme.autoNightSunsetTime = time[1];
    Theme.autoNightCityName = null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    Theme.autoNightLastSunCheckDay = calendar.get(Calendar.DAY_OF_MONTH);
    Utilities.globalQueue.postRunnable(() -> {
        String name;
        try {
            Geocoder gcd = new Geocoder(ApplicationLoader.applicationContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(Theme.autoNightLocationLatitude,
                    Theme.autoNightLocationLongitude, 1);
            if (addresses.size() > 0) {
                name = addresses.get(0).getLocality();
            } else {
                name = null;
            }
        } catch (Exception ignore) {
            name = null;
        }
        final String nameFinal = name;
        AndroidUtilities.runOnUIThread(() -> {
            Theme.autoNightCityName = nameFinal;
            if (Theme.autoNightCityName == null) {
                Theme.autoNightCityName = String.format("(%.06f, %.06f)", Theme.autoNightLocationLatitude,
                        Theme.autoNightLocationLongitude);
            }
            Theme.saveAutoNightThemeConfig();
            if (listView != null) {
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
                        .findViewHolderForAdapterPosition(scheduleUpdateLocationRow);
                if (holder != null && holder.itemView instanceof TextSettingsCell) {
                    ((TextSettingsCell) holder.itemView).setTextAndValue(LocaleController
                            .getString("AutoNightUpdateLocation", R.string.AutoNightUpdateLocation),
                            Theme.autoNightCityName, false);
                }
            }
        });
    });
    RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
            .findViewHolderForAdapterPosition(scheduleLocationInfoRow);
    if (holder != null && holder.itemView instanceof TextInfoPrivacyCell) {
        ((TextInfoPrivacyCell) holder.itemView).setText(getLocationSunString());
    }
    if (Theme.autoNightScheduleByLocation && Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
        Theme.checkAutoNightThemeConditions();
    }
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

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

    /* resume location query */
    if (locationEnabled) {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationTracker);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationTracker);
    }/*from www .j a v  a2  s . c o m*/
}

From source file:de.vanita5.twittnuker.activity.support.ComposeActivity.java

private void updateStatus() {
    if (isFinishing())
        return;/* ww w  . ja va  2 s. c  o  m*/
    final boolean hasMedia = hasMedia();
    final String text = mEditText != null ? ParseUtils.parseString(mEditText.getText()) : null;
    final int tweetLength = mValidator.getTweetLength(text), maxLength = mValidator.getMaxTweetLength();
    if (!mStatusShortenerUsed && tweetLength > maxLength) {
        mEditText.setError(getString(R.string.error_message_status_too_long));
        final int text_length = mEditText.length();
        mEditText.setSelection(text_length - (tweetLength - maxLength), text_length);
        return;
    } else if (!hasMedia && (isEmpty(text) || noReplyContent(text))) {
        mEditText.setError(getString(R.string.error_message_no_content));
        return;
    }
    final boolean attach_location = mPreferences.getBoolean(KEY_ATTACH_LOCATION, false);
    if (mRecentLocation == null && attach_location) {
        final Location location;
        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = null;
        }
        mRecentLocation = location != null ? new ParcelableLocation(location) : null;
    }
    final boolean isQuote = INTENT_ACTION_QUOTE.equals(getIntent().getAction());
    final ParcelableLocation statusLocation = attach_location ? mRecentLocation : null;
    final boolean linkToQuotedTweet = mPreferences.getBoolean(KEY_LINK_TO_QUOTED_TWEET, true);
    final long inReplyToStatusId = !isQuote || linkToQuotedTweet ? mInReplyToStatusId : -1;
    final boolean isPossiblySensitive = hasMedia && mIsPossiblySensitive;
    mTwitterWrapper.updateStatusAsync(mSendAccountIds, text, statusLocation, getMedias(), inReplyToStatusId,
            isPossiblySensitive);
    if (mPreferences.getBoolean(KEY_NO_CLOSE_AFTER_TWEET_SENT, false)
            && (mInReplyToStatus == null || mInReplyToStatusId <= 0)) {
        mIsPossiblySensitive = false;
        mShouldSaveAccounts = true;
        mTempPhotoUri = null;
        mInReplyToStatus = null;
        mMentionUser = null;
        mDraftItem = null;
        mInReplyToStatusId = -1;
        mOriginalText = null;
        mEditText.setText(null);
        clearMedia();
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        setIntent(intent);
        setComposeTitle(intent);
        handleIntent(intent);
        setMenu();
        updateTextCount();
    } else {
        setResult(Activity.RESULT_OK);
        finish();
    }
}

From source file:com.davidmascharka.lips.TrackerActivity.java

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

    File root = Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + "/indoor_localization");
    dir.mkdirs();//from   ww w.ja  va  2s. c om
    file = new File(dir, "livetest_" + building + ".txt");
    valuesFile = new File(dir, "livetest_" + building + "_values.txt");
    try {
        outputStream = new FileOutputStream(file, true);
        valuesOutputStream = new FileOutputStream(valuesFile, true);
        writer = new PrintWriter(outputStream);
        valuesWriter = new PrintWriter(valuesOutputStream);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set building textview to the building the user has selected
    //TextView buildingText = (TextView) findViewById(R.id.text_building);
    //buildingText.setText("Building: " + building);

    // Set room size textview to the room size the user has selected
    //TextView roomSizeText = (TextView) findViewById(R.id.text_room_size);
    //roomSizeText.setText("Room size: " + roomWidth + " x " + roomLength);

    // Set grid options
    GridView grid = (GridView) findViewById(R.id.tracker_gridView);
    //grid.setGridSize(roomWidth, roomLength);
    grid.setGridSize(102, 64);
    grid.setCatchInput(false);
    //grid.setDisplayMap(displayMap);

    // Register to get sensor updates from all the available sensors
    sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
    for (Sensor sensor : sensorList) {
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    // Enable wifi if it is disabled
    if (!wifiManager.isWifiEnabled()) {
        Toast.makeText(this, "WiFi not enabled. Enabling...", Toast.LENGTH_SHORT).show();
        wifiManager.setWifiEnabled(true);
    }

    // Request location updates from gps and the network
    //@author Mahesh Gaya added permission if-statment
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permissions have NOT been granted. Requesting permissions.");
        requestMyPermissions();
    } else {
        Log.i(TAG, "Permissions have already been granted. Getting location from GPS and Network");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }

    registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    wifiManager.startScan();
    Toast.makeText(this, "Initiated scan", Toast.LENGTH_SHORT).show();

    xText = (TextView) findViewById(R.id.tracker_text_xcoord);
    yText = (TextView) findViewById(R.id.tracker_text_ycoord);
}

From source file:org.telegram.ui.ThemeActivity.java

private void startLocationUpdate() {
    if (updatingLocation) {
        return;//from  www .  ja  v  a 2  s .  c om
    }
    updatingLocation = true;
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, gpsLocationListener);
    } catch (Exception e) {
        FileLog.e(e);
    }
    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, networkLocationListener);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:org.mariotaku.twidere.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*from  www.ja  v a  2s .  c om*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:org.ohmage.reminders.types.location.LocTrigService.java

@Override
public void onLocationChanged(Location loc) {
    Log.v(TAG,//  ww w  . j a  v a 2  s .  c om
            "LocTrigService: new location received: " + loc.getLatitude() + ", " + loc.getLongitude() + " ("
                    + loc.getProvider() + "), accuracy = " + loc.getAccuracy() + ", speed = " + loc.getSpeed()
                    + ", Time = " + new Date(loc.getTime()).toString());

    if (!mGPSStarted) {
        Log.v(TAG, "LocTrigService: Discarding stray location " + "after disabling locaiton updates");
        return;
    }

    //Discard if a stale location is received (could be possible in network
    //location)
    if ((loc.getTime() + STALE_LOC_TIME) < System.currentTimeMillis()) {
        Log.v(TAG, "LocTrigService: Discarding stale location");
        return;
    }

    /* Check if the last known location belongs to a category.
     * This is required when the user defines a category on the current
     * location. At this time, the surveys must not be
     * immediately triggered but only when the user enters this
     * category the next time. Thus, at this point, check if the last
     * known location has a category. This means that the last known location
     * must not be triggered.
     *
     * There is a corner case where this will not work. Suppose, the user entered
     * a location and the GPS sampling hasn't been done yet. So, this location is
     * not yet recorded. If the user defines a new category on this location and
     * sets triggers, it will be triggered. This can happen only if the user sets
     * a trigger with in MAX_SLEEP_TIME after entering a location.
     */
    int prevCateg = getLocCategory(mLastKnownLoc);
    if (prevCateg != CATEG_ID_INVAL && mLatestCateg == CATEG_ID_INVAL) {
        Log.v(TAG, "LocTrigService: Assigning category to the prev loc");
        recordLatestCategory(prevCateg);
    }

    if (!loc.hasAccuracy()) {
        Log.v(TAG, "LocTrigService: Discarding loc with no accuracy info");
        return;
    }

    recordLocation(loc);

    int locCateg = getLocCategory(loc);
    Log.v(TAG, "LocTrigService: Loc category = " + locCateg);

    if (locCateg != CATEG_ID_INVAL) {
        handlePassThroughCheckIfRequired(locCateg);

        //If entering a new category, trigger if necessary
        //set the pass through check alarm first
        if (locCateg != mLatestCateg) {
            //start triggering only after sufficient number of
            //initial samples have been collected
            if (mNInitialSamples >= SAMPLES_LIMIT) {

                //Cache the previous visit time for this category
                //as it is going to be updated now
                LocTrigDB db = new LocTrigDB(this);
                db.open();
                mCategPrevTS = db.getCategoryTimeStamp(locCateg);
                Log.v(TAG, "LocTrigService: Caching category time stamp: " + mCategPrevTS);

                db.close();

                setSamplingAlarm(ACTION_ALRM_PASS_THROUGH, PASS_THROUGH_TIME, locCateg);
            }
        }

        recordLatestCategory(locCateg);

        mNInitialSamples = SAMPLES_LIMIT;
        mNSamples = SAMPLES_LIMIT;
        mCurrSpeed = 0;

        reScheduleGPS();
        return;
    } else {
        //Discard very inaccurate samples
        if (loc.getAccuracy() > INACCURATE_SAMPLE_THRESHOLD) {
            /* Refresh the time stamp of the latest category.
             * If the user enters a building within a category
             * then that category might expire due to inaccurate
             * samples. Refreshing the time stamp will prevent
             * duplicate triggers from happening at that category
             */
            recordLatestCategory(mLatestCateg);

            Log.v(TAG, "LocTrigService: Discarding inaccurate sample");
            return;
        }

        //Detect an exit from a category and start aggressive sampling
        if (mLatestCateg != CATEG_ID_INVAL) {
            resetSleepTime();
        }

        recordLatestCategory(locCateg);

        //Do not turn off updates until sufficient samples with speed info
        //are obtained
        if (LocTrigConfig.useNetworkLocation) {
            if (loc.getProvider().equals(LocationManager.NETWORK_PROVIDER) && !loc.hasSpeed()) {
                Log.v(TAG, "LocTrigService: Discarding network " + "location without speed");
                return;
            }
        }

        recordSpeed(loc);

        //Collect some initial samples when the service/sampling starts for
        //the first time. This is to establish the current location.
        //This makes sure than the very first trigger set on the current
        //location is not triggered immediately.
        if (mNInitialSamples < SAMPLES_LIMIT) {
            mNInitialSamples++;

            Log.v(TAG, "LocTrigService: Collecting initial samples");
            return;
        }

        mNSamples++;
        //If the sample count hits the limit, reschedule.
        if (mNSamples == SAMPLES_LIMIT) {
            cancelPassThroughCheckingIfRequired();
            reScheduleGPS();
        }
    }
}

From source file:com.davidmascharka.lips.TrackerActivity.java

/**
 * When a new WiFi scan comes in, get sensor values and predict position
 *///from w  ww .j  a  va2 s.  com
private void updateScanResults() {
    resetWifiReadings();

    scanResults = wifiManager.getScanResults();

    // Start another scan to recalculate user position
    wifiManager.startScan();

    time = new Timestamp(System.currentTimeMillis());

    for (ScanResult result : scanResults) {
        if (wifiReadings.get(result.BSSID) != null) {
            wifiReadings.put(result.BSSID, result.level);
        } // else BSSID wasn't programmed in
    }
    //@author Mahesh Gaya added permission if-statment
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permissions have NOT been granted. Requesting permissions.");
        requestMyPermissions();
    } else {
        Log.i(TAG, "Permissions have already been granted. Getting last known location from GPS and Network");
        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if (location == null) {
            locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
    }
    setInstanceValues();

    printValues();

    // this is where the magic happens
    // TODO clean up
    if (!t.isAlive()) {
        t = new Thread(new Runnable() {
            public void run() {
                Timestamp myTime = time;
                // This doesn't do anything -> classifierXKStar is null -> not loaded
                /*try {
                   predictedX = (float) classifierXRBFRegressor.classifyInstance(xInstances.get(0));
                } catch (Exception e) {
                   e.printStackTrace();
                }
                // Likewise, doesn't happen
                try {
                   predictedY = (float) classifierYRBFRegressor.classifyInstance(yInstances.get(0));
                } catch (Exception e) {
                   e.printStackTrace();
                }*/

                // Get the partition that the new instance is in
                // Use the classifier of the predicted partition to predict an x and y value for
                // the new instance if the classifier is loaded (not null)
                try {
                    predictedPartition = partitionClassifier.classifyInstance(partitionInstances.get(0));
                    //double[] dist = partitionClassifier.distributionForInstance(partitionInstances.get(0)); // gets the probability distribution for the instance
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String partitionString = partitionInstances.classAttribute().value((int) predictedPartition);
                if (partitionString.equals("upperleft")) {
                    if (partitionUpperLeftX != null) {
                        try {
                            predictedX = (float) partitionUpperLeftX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionUpperLeftY != null) {
                        try {
                            predictedY = (float) partitionUpperLeftY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("upperright")) {
                    if (partitionUpperRightX != null) {
                        try {
                            predictedX = (float) partitionUpperRightX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionUpperRightY != null) {
                        try {
                            predictedY = (float) partitionUpperRightY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("lowerleft")) {
                    if (partitionLowerLeftX != null) {
                        try {
                            predictedX = (float) partitionLowerLeftX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionLowerLeftY != null) {
                        try {
                            predictedY = (float) partitionLowerLeftY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("lowerright")) {
                    if (partitionLowerRightX != null) {
                        try {
                            predictedX = (float) partitionLowerRightX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionLowerRightY != null) {
                        try {
                            predictedY = (float) partitionLowerRightY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("middle")) {
                    if (partitionMiddleX != null) {
                        try {
                            predictedX = (float) partitionMiddleX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionMiddleX != null) {
                        try {
                            predictedY = (float) partitionMiddleY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                xText.post(new Runnable() {
                    public void run() {
                        xText.setText("X Position: " + predictedX);
                    }
                });

                yText.post(new Runnable() {
                    public void run() {
                        yText.setText("Y Position: " + predictedY);
                    }
                });

                // TODO: make this work -> grid is apparently null here. For whatever reason.
                /*runOnUiThread(new Runnable() {
                   public void run() {
                      grid.setUserPointCoords(predictedX, predictedY);
                   }
                });*/

                // Unnecessary if you're not testing
                writer.print("(" + predictedX + "," + predictedY + ")");
                writer.print(" %" + myTime.toString() + "\t " + time.toString() + "\t"
                        + new Timestamp(System.currentTimeMillis()) + "\n");
                writer.flush();
            }
        });
        t.setPriority(Thread.MIN_PRIORITY); // run in the background
        t.start();
    }
}

From source file:org.ohmage.triggers.types.location.LocTrigService.java

@Override
public void onLocationChanged(Location loc) {
    Log.i(DEBUG_TAG,/* www.  j  a va 2 s. com*/
            "LocTrigService: new location received: " + loc.getLatitude() + ", " + loc.getLongitude() + " ("
                    + loc.getProvider() + "), accuracy = " + loc.getAccuracy() + ", speed = " + loc.getSpeed()
                    + ", Time = " + new Date(loc.getTime()).toString());

    if (!mGPSStarted) {
        Log.i(DEBUG_TAG, "LocTrigService: Discarding stray location " + "after disabling locaiton updates");
        return;
    }

    //Discard if a stale location is received (could be possible in network
    //location)
    if ((loc.getTime() + STALE_LOC_TIME) < System.currentTimeMillis()) {
        Log.i(DEBUG_TAG, "LocTrigService: Discarding stale location");
        return;
    }

    /* Check if the last known location belongs to a category. 
     * This is required when the user defines a category on the current
     * location. At this time, the surveys must not be 
     * immediately triggered but only when the user enters this
     * category the next time. Thus, at this point, check if the last
     * known location has a category. This means that the last known location
     * must not be triggered. 
     * 
     * There is a corner case where this will not work. Suppose, the user entered
     * a location and the GPS sampling hasn't been done yet. So, this location is 
     * not yet recorded. If the user defines a new category on this location and
     * sets triggers, it will be triggered. This can happen only if the user sets
     * a trigger with in MAX_SLEEP_TIME after entering a location. 
     */
    int prevCateg = getLocCategory(mLastKnownLoc);
    if (prevCateg != CATEG_ID_INVAL && mLatestCateg == CATEG_ID_INVAL) {
        Log.i(DEBUG_TAG, "LocTrigService: Assigning category to the prev loc");
        recordLatestCategory(prevCateg);
    }

    if (!loc.hasAccuracy()) {
        Log.i(DEBUG_TAG, "LocTrigService: Discarding loc with no accuracy info");
        return;
    }

    recordLocation(loc);

    int locCateg = getLocCategory(loc);
    Log.i(DEBUG_TAG, "LocTrigService: Loc category = " + locCateg);

    if (locCateg != CATEG_ID_INVAL) {
        handlePassThroughCheckIfRequired(locCateg);

        //If entering a new category, trigger if necessary
        //set the pass through check alarm first
        if (locCateg != mLatestCateg) {
            //start triggering only after sufficient number of
            //initial samples have been collected
            if (mNInitialSamples >= SAMPLES_LIMIT) {

                //Cache the previous visit time for this category
                //as it is going to be updated now
                LocTrigDB db = new LocTrigDB(this);
                db.open();
                mCategPrevTS = db.getCategoryTimeStamp(locCateg);
                Log.i(DEBUG_TAG, "LocTrigService: Caching category time stamp: " + mCategPrevTS);

                db.close();

                setSamplingAlarm(ACTION_ALRM_PASS_THROUGH, PASS_THROUGH_TIME, locCateg);
            }
        }

        recordLatestCategory(locCateg);

        mNInitialSamples = SAMPLES_LIMIT;
        mNSamples = SAMPLES_LIMIT;
        mCurrSpeed = 0;

        reScheduleGPS();
        return;
    } else {
        //Discard very inaccurate samples
        if (loc.getAccuracy() > INACCURATE_SAMPLE_THRESHOLD) {
            /* Refresh the time stamp of the latest category.
             * If the user enters a building within a category
             * then that category might expire due to inaccurate
             * samples. Refreshing the time stamp will prevent
             * duplicate triggers from happening at that category
             */
            recordLatestCategory(mLatestCateg);

            Log.i(DEBUG_TAG, "LocTrigService: Discarding inaccurate sample");
            return;
        }

        //Detect an exit from a category and start aggressive sampling
        if (mLatestCateg != CATEG_ID_INVAL) {
            resetSleepTime();
        }

        recordLatestCategory(locCateg);

        //Do not turn off updates until sufficient samples with speed info
        //are obtained
        if (LocTrigConfig.useNetworkLocation) {
            if (loc.getProvider().equals(LocationManager.NETWORK_PROVIDER) && !loc.hasSpeed()) {
                Log.i(DEBUG_TAG, "LocTrigService: Discarding network " + "location without speed");
                return;
            }
        }

        recordSpeed(loc);

        //Collect some initial samples when the service/sampling starts for
        //the first time. This is to establish the current location.
        //This makes sure than the very first trigger set on the current
        //location is not triggered immediately.
        if (mNInitialSamples < SAMPLES_LIMIT) {
            mNInitialSamples++;

            Log.i(DEBUG_TAG, "LocTrigService: Collecting initial samples");
            return;
        }

        mNSamples++;
        //If the sample count hits the limit, reschedule.
        if (mNSamples == SAMPLES_LIMIT) {
            cancelPassThroughCheckingIfRequired();
            reScheduleGPS();
        }
    }
}