Example usage for android.content Context LOCATION_SERVICE

List of usage examples for android.content Context LOCATION_SERVICE

Introduction

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

Prototype

String LOCATION_SERVICE

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

Click Source Link

Document

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

Usage

From source file:com.mobilyzer.util.PhoneUtils.java

/**
 * Lazily initializes the location manager.
 *
 * As a side effect, assigns locationManager and locationProviderName.
 *//*from  w  ww . j ava 2  s . com*/
private synchronized void initLocation() {
    if (locationManager == null) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        Criteria criteriaCoarse = new Criteria();
        /* "Coarse" accuracy means "no need to use GPS".
         * Typically a gShots phone would be located in a building,
         * and GPS may not be able to acquire a location.
         * We only care about the location to determine the country,
         * so we don't need a super accurate location, cell/wifi is good enough.
         */
        criteriaCoarse.setAccuracy(Criteria.ACCURACY_COARSE);
        criteriaCoarse.setPowerRequirement(Criteria.POWER_LOW);
        String providerName = manager.getBestProvider(criteriaCoarse, /*enabledOnly=*/true);

        List<String> providers = manager.getAllProviders();
        for (String providerNameIter : providers) {
            try {
                LocationProvider provider = manager.getProvider(providerNameIter);
            } catch (SecurityException se) {
                // Not allowed to use this provider
                Logger.w("Unable to use provider " + providerNameIter);
                continue;
            }
            Logger.i(providerNameIter + ": "
                    + (manager.isProviderEnabled(providerNameIter) ? "enabled" : "disabled"));
        }

        /* Make sure the provider updates its location.
         * Without this, we may get a very old location, even a
         * device powercycle may not update it.
         * {@see android.location.LocationManager.getLastKnownLocation}.
         */
        manager.requestLocationUpdates(providerName, /*minTime=*/0, /*minDistance=*/0,
                new LoggingLocationListener(), Looper.getMainLooper());
        locationManager = manager;
        locationProviderName = providerName;
    }
    assert locationManager != null;
    assert locationProviderName != null;
}

From source file:com.snt.bt.recon.activities.MainActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.snt.bt.recon.R.layout.activity_main);
    ButterKnife.bind(this);
    logDebug("Activity", "######################## On Create ########################");
    //Lock orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //Leave screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    //leave cpu on
    wl = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "wlTag");
    wl.acquire();//from w w  w  .ja  va2  s .  c om

    //For device id
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    //for connectivity
    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    try {

        logDebug("DatabaseTest", "Reading all trips..");
        List<Trip> trips = db.getAll(Trip.class);
        for (Trip trip : trips) {
            String log = "session id: " + trip.getSessionId() + " imei: " + trip.getImei() + " transport: "
                    + trip.getTransport() + " TS: " + trip.getTimestampStart() + " TE: "
                    + trip.getTimestampEnd() + " upload status: " + trip.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all locations..");
        List<GPSLocation> locs = db.getAll(GPSLocation.class);
        for (GPSLocation loc : locs) {
            String log = "loc id: " + loc.getLocationId() + " sess id: " + loc.getSessionId() + " timestamp: "
                    + loc.getTimestamp() + " upload status: " + loc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all bc..");
        List<BluetoothClassicEntry> bcs = db.getAll(BluetoothClassicEntry.class);
        for (BluetoothClassicEntry bc : bcs) {
            String log = "sess id: " + bc.getSessionId() + " loc id: " + bc.getLocationId() + " upload status: "
                    + bc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all ble..");
        List<BluetoothLowEnergyEntry> bles = db.getAll(BluetoothLowEnergyEntry.class);
        for (BluetoothLowEnergyEntry ble : bles) {
            String log = "sess id: " + ble.getSessionId() + " loc id: " + ble.getLocationId()
                    + " upload status: " + ble.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

    //Show select transpot mode
    new TransportMode(this).show();

    // Show EULA
    new AppEULA(this).show();

    //displayFeedbackDialog();

    //avtivity recognition start
    mActivityRecognitionScan = new ActivityRecognitionUtil(this);
    mActivityRecognitionScan.startActivityRecognitionScan();
    //Filter the Intent and register broadcast receiver
    registerReceiver(ActivityRecognitionReceiver, new IntentFilter("ImActive"));

    //gps
    gpsStatusCheck();

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);

    //bt
    mBluetoothUtils = new BluetoothUtils(this);

    //ble
    mLeDeviceStore = new BluetoothLeDeviceStore();
    mLeScanner = new BluetoothLeScanner(mLeScanCallback, mBluetoothUtils);
    //bc
    mBcDeviceList = new ArrayList<>();

    final Handler h = new Handler();
    final int delay = 60000;

    h.postDelayed(new Runnable() {
        public void run() {
            syncServerDatabase();

            h.postDelayed(this, delay);
        }
    }, delay);

    //Clean BLE table in case device last timestamp is > 10 seconds
    final Handler h2 = new Handler();
    h2.postDelayed(new Runnable() {
        public void run() {
            //clear old ble devices
            for (BluetoothLeDevice device : mLeDeviceStore.getDeviceList()) {
                long diff = System.currentTimeMillis() - device.getTimestamp();
                if (diff > 10000) {
                    mLeDeviceStore.removeDevice(device);
                    //Refresh the listview
                    final EasyObjectCursor<BluetoothLeDevice> c = mLeDeviceStore.getDeviceCursor();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLeDeviceListAdapter.swapCursor(c);
                        }
                    });
                }
            }

            h2.postDelayed(this, 1000);//1 sec
        }
    }, 1000);
}

From source file:fashiome.android.fragments.MapListFragment.java

private LatLng getLastKnownLocation(boolean isMoveMarker) {
    LocationManager lm = (LocationManager) AppStarter.getAppContext()
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }//  w  w  w .  j ava 2  s  .c om
    Activity activity = getActivity();
    if (activity == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && activity.checkSelfPermission(
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    }
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
        if (isMoveMarker) {
            moveMarker(latLng);
        }
        return latLng;
    }
    return null;
}

From source file:com.umaps.gpslogger.GpsLoggingService.java

/**
 * Starts the location manager. There are two location managers - GPS and
 * Cell Tower. This code determines which manager to request updates from
 * based on user preference and whichever is enabled. If GPS is enabled on
 * the phone, that is used. But if the user has also specified that they
 * prefer cell towers, then cell towers are used. If neither is enabled,
 * then nothing is requested.//from   ww w .  ja  v  a2s  .c o m
 */
private void StartGpsManager() {

    GetPreferences();

    //If the user has been still for more than the minimum seconds
    if (userHasBeenStillForTooLong()) {
        Log.i(TAG, "No movement detected in the past interval, will not log");
        SetAlarmForNextPoint();
        return;
    }

    if (gpsLocationListener == null) {
        gpsLocationListener = new GeneralLocationListener(this, "GPS");
    }

    if (towerLocationListener == null) {
        towerLocationListener = new GeneralLocationListener(this, "CELL");
    }

    gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    towerLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    CheckTowerAndGpsStatus();

    if (Session.isGpsEnabled() && AppSettings.getChosenListeners().contains("gps")) {
        Log.i(TAG, "Requesting GPS location updates");
        // gps satellite based
        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);
        gpsLocationManager.addGpsStatusListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();
    }

    if (Session.isTowerEnabled()
            && (AppSettings.getChosenListeners().contains("network") || !Session.isGpsEnabled())) {
        Log.i(TAG, "Requesting cell and wifi location updates");
        Session.setUsingGps(false);
        // Cell tower and wifi based
        towerLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                towerLocationListener);

        startAbsoluteTimer();
    }

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        Log.e(TAG, "No provider available!");
        Session.setUsingGps(false);
        Log.e(TAG, getString(R.string.gpsprovider_unavailable));
        StopLogging();
        SetLocationServiceUnavailable();
        return;
    }

    EventBus.getDefault().post(new ServiceEvents.WaitingForLocation(true));
    Session.setWaitingForLocation(true);
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    mService = getTweetingsApplication().getServiceInterface();
    mResolver = getContentResolver();/*  w  w  w .  jav a 2s . c  om*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.compose);
    mActionBar = getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(true);

    mUploadProvider = mPreferences.getString(PREFERENCE_KEY_IMAGE_UPLOADER, null);

    final Bundle bundle = savedInstanceState != null ? savedInstanceState : getIntent().getExtras();
    final long account_id = bundle != null ? bundle.getLong(INTENT_KEY_ACCOUNT_ID) : -1;
    mAccountIds = bundle != null ? bundle.getLongArray(INTENT_KEY_IDS) : null;
    mInReplyToStatusId = bundle != null ? bundle.getLong(INTENT_KEY_IN_REPLY_TO_ID) : -1;
    mInReplyToScreenName = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME) : null;
    mInReplyToName = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_NAME) : null;
    mInReplyToText = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_TWEET) : null;
    mIsImageAttached = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_IMAGE_ATTACHED) : false;
    mIsPhotoAttached = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_PHOTO_ATTACHED) : false;
    mImageUri = bundle != null ? (Uri) bundle.getParcelable(INTENT_KEY_IMAGE_URI) : null;
    final String[] mentions = bundle != null ? bundle.getStringArray(INTENT_KEY_MENTIONS) : null;
    final String account_username = getAccountUsername(this, account_id);
    int text_selection_start = -1;
    mIsBuffer = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_BUFFER, false) : false;

    if (mInReplyToStatusId > 0) {
        if (bundle != null && bundle.getString(INTENT_KEY_TEXT) != null
                && (mentions == null || mentions.length < 1)) {
            mText = bundle.getString(INTENT_KEY_TEXT);
        } else if (mentions != null) {
            final StringBuilder builder = new StringBuilder();
            for (final String mention : mentions) {
                if (mentions.length == 1 && mentions[0].equalsIgnoreCase(account_username)) {
                    builder.append('@' + account_username + ' ');
                } else if (!mention.equalsIgnoreCase(account_username)) {
                    builder.append('@' + mention + ' ');
                }
            }
            mText = builder.toString();
            text_selection_start = mText.indexOf(' ') + 1;
        }

        mIsQuote = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_QUOTE, false) : false;

        final boolean display_name = mPreferences.getBoolean(PREFERENCE_KEY_DISPLAY_NAME, false);
        final String name = display_name ? mInReplyToName : mInReplyToScreenName;
        if (name != null) {
            setTitle(getString(mIsQuote ? R.string.quote_user : R.string.reply_to, name));
        }
        if (mAccountIds == null || mAccountIds.length == 0) {
            mAccountIds = new long[] { account_id };
        }
        TextView replyText = (TextView) findViewById(R.id.reply_text);
        if (!isNullOrEmpty(mInReplyToText)) {
            replyText.setVisibility(View.VISIBLE);
            replyText.setText(mInReplyToText);
        } else {
            replyText.setVisibility(View.GONE);
        }
    } else {
        if (mentions != null) {
            final StringBuilder builder = new StringBuilder();
            for (final String mention : mentions) {
                if (mentions.length == 1 && mentions[0].equalsIgnoreCase(account_username)) {
                    builder.append('@' + account_username + ' ');
                } else if (!mention.equalsIgnoreCase(account_username)) {
                    builder.append('@' + mention + ' ');
                }
            }
            mText = builder.toString();
        }
        if (mAccountIds == null || mAccountIds.length == 0) {
            final long[] ids_in_prefs = ArrayUtils
                    .fromString(mPreferences.getString(PREFERENCE_KEY_COMPOSE_ACCOUNTS, null), ',');
            final long[] activated_ids = getActivatedAccountIds(this);
            final long[] intersection = ArrayUtils.intersection(ids_in_prefs, activated_ids);
            mAccountIds = intersection.length > 0 ? intersection : activated_ids;
        }
        final String action = getIntent().getAction();
        if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
            setTitle(R.string.share);
            final Bundle extras = getIntent().getExtras();
            if (extras != null) {
                if (mText == null) {
                    final CharSequence extra_subject = extras.getCharSequence(Intent.EXTRA_SUBJECT);
                    final CharSequence extra_text = extras.getCharSequence(Intent.EXTRA_TEXT);
                    mText = getShareStatus(this, parseString(extra_subject), parseString(extra_text));
                } else {
                    mText = bundle.getString(INTENT_KEY_TEXT);
                }
                if (mImageUri == null) {
                    final Uri extra_stream = extras.getParcelable(Intent.EXTRA_STREAM);
                    final String content_type = getIntent().getType();
                    if (extra_stream != null && content_type != null && content_type.startsWith("image/")) {
                        final String real_path = getImagePathFromUri(this, extra_stream);
                        final File file = real_path != null ? new File(real_path) : null;
                        if (file != null && file.exists()) {
                            mImageUri = Uri.fromFile(file);
                            mIsImageAttached = true;
                            mIsPhotoAttached = false;
                        } else {
                            mImageUri = null;
                            mIsImageAttached = false;
                        }
                    }
                }
            }
        } else if (bundle != null) {

            if (bundle.getString(INTENT_KEY_TEXT) != null) {
                mText = bundle.getString(INTENT_KEY_TEXT);
            }
        }
    }

    final File image_file = mImageUri != null && "file".equals(mImageUri.getScheme())
            ? new File(mImageUri.getPath())
            : null;
    final boolean image_file_valid = image_file != null && image_file.exists();
    mImageThumbnailPreview.setVisibility(image_file_valid ? View.VISIBLE : View.GONE);
    if (image_file_valid) {
        reloadAttachedImageThumbnail(image_file);
    }

    mImageThumbnailPreview.setOnClickListener(this);
    mImageThumbnailPreview.setOnLongClickListener(this);
    mMenuBar.setOnMenuItemClickListener(this);
    mMenuBar.inflate(R.menu.menu_compose);
    mMenuBar.show();
    if (mPreferences.getBoolean(PREFERENCE_KEY_QUICK_SEND, false)) {
        mEditText.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
        mEditText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
        mEditText.setImeOptions(EditorInfo.IME_ACTION_GO);
        mEditText.setOnEditorActionListener(this);
    }
    mEditText.addTextChangedListener(this);
    if (mText != null) {
        mEditText.setText(mText);
        if (mIsQuote) {
            mEditText.setSelection(0);
        } else if (text_selection_start != -1 && text_selection_start < mEditText.length()
                && mEditText.length() > 0) {
            mEditText.setSelection(text_selection_start, mEditText.length() - 1);
        } else if (mEditText.length() > 0) {
            mEditText.setSelection(mEditText.length());
        }
    }
    invalidateSupportOptionsMenu();
    setMenu();
    if (mColorIndicator != null) {
        mColorIndicator.setOrientation(ColorView.VERTICAL);
        mColorIndicator.setColor(getAccountColors(this, mAccountIds));
    }
    mContentModified = savedInstanceState != null ? savedInstanceState.getBoolean(INTENT_KEY_CONTENT_MODIFIED)
            : false;
    mIsPossiblySensitive = savedInstanceState != null
            ? savedInstanceState.getBoolean(INTENT_KEY_IS_POSSIBLY_SENSITIVE)
            : false;
}

From source file:com.tml.sharethem.receiver.ReceiverActivity.java

private boolean checkLocationAccess() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Log.e(TAG, "GPS not enabled..");
        buildAlertMessageNoGps();/*from  w w w  . java  2 s.  c  o m*/
        return false;
    }
    return true;
}

From source file:com.waz.zclient.pages.main.conversation.LocationFragment.java

private boolean isLocationServicesEnabled() {
    if (!PermissionUtils.hasSelfPermissions(getContext(), LOCATION_PERMISSIONS)) {
        return false;
    }// w  w  w .j  a  v  a2  s  .  co m
    // We are creating a local locationManager here, as it's not sure we already have one
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager == null) {
        return false;
    }
    boolean gpsEnabled;
    boolean netEnabled;

    try {
        gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception e) {
        gpsEnabled = false;
    }

    try {
        netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        netEnabled = false;
    }
    return netEnabled || gpsEnabled;
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java

private boolean checkCurrentLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }/*from w  w w .j  a  v  a  2 s  .co m*/
    locationManager = (LocationManager) getActivity().getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);

    final List<String> providers = locationManager.getProviders(true);
    Location finalLocation = null;

    for (final String provider : providers) {
        final Location lastKnown = locationManager.getLastKnownLocation(provider);
        if (lastKnown == null) {
            continue;
        }
        if (finalLocation == null || (lastKnown.getAccuracy() < finalLocation.getAccuracy())) {
            finalLocation = lastKnown;
        }
    }
    location = finalLocation;
    return location != null;
}

From source file:com.wishlist.Wishlist.java

public void fetchCurrentLocation() {
    new Thread() {
        public void run() {
            Looper.prepare();/*w  ww. java2  s.  c  o m*/
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            MyLocationListener locationListener = new MyLocationListener();
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = mLocationManager.getBestProvider(criteria, true);
            if (provider != null && mLocationManager.isProviderEnabled(provider)) {
                mLocationManager.requestLocationUpdates(provider, 1, 0, locationListener,
                        Looper.getMainLooper());
            } else {
                showToast("Please turn on handset's GPS");
            }
            Looper.loop();
        }
    }.start();
}

From source file:com.zainsoft.ramzantimetable.QiblaActivity.java

private void checkForGPSnShowQibla() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();/*  w  w  w .  j  a v a2s.c o m*/
        Log.d(TAG, "GPS is OFF");
    } else {
        Log.d(TAG, "GPS is ON");
        registerForGPS();
        onGPSOn();
    }
}