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.kentli.cycletrack.RecordingService.java

public void resumeRecording() {
    this.state = STATE_RECORDING;
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}

From source file:biz.bokhorst.bpt.BPTService.java

@Override
public IBinder onBind(Intent intent) {
    // Start foreground service
    startForeground(1, getNotification(getString(R.string.Running)));

    // Instantiate helpers
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    databaseHelper = new DatabaseHelper(this);
    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    taskHandler = new Handler();
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BPT");
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    Intent alarmIntent = new Intent("BPT_ALARM");
    pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmReceiver = new BPTAlarmReceiver();
    registerReceiver(alarmReceiver, new IntentFilter("BPT_ALARM"));

    bound = true;//from w w  w  .ja va2 s.  com
    return serverMessenger.getBinder();
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

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

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    TextView tv1 = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.fileLocation);
    ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    tv1.setText("Name : " + Session.name);
    tv2.setText("Caption :" + Session.caption);
    iv1.setImageBitmap(Session.image);
    tv3.setVisibility(View.GONE);
    //tv3.setText(Session.fileLocation2);
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

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

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                String[] res = ((String) msg.obj).split(",");
                lat = res[0];
                longt = res[1];
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mBothProviderButton.performClick();
    btnUpload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                executeMultipartPost();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

From source file:com.warp10.app.LocationService.java

/**
 * Handler of action Start//from  ww w .  ja  v  a  2 s  .com
 * @param isListenGPS if asked register GPS
 * @param isListenNetWork if asked register Network location
 */
private void handleActionStart(boolean isListenGPS, boolean isListenNetWork, final Context context,
        boolean recGPS, boolean recNetwork, final String prefixGTS) {
    // Define a listener that responds to location updates

    if (isRunning) {
        this.onDestroy();
    }
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    final boolean record = recGPS || recNetwork;

    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (record) {
                //Log.d("GPSLOCA",location.toString());
                long timestamp = System.currentTimeMillis() * 1000;
                // If buffer have full size
                if (null == stringBuffer) {
                    stringBuffer = new StringBuffer();
                }
                if (stringBuffer.length() >= BUFFER_SIZE) {
                    emptyBuffer();
                }
                if (stringBuffer.length() > 0) {
                    stringBuffer.append("\n");
                }
                String fix = "";
                /**
                 if(prefixGTS.equals(new String()))
                 {
                 prefixGTS = "android";
                 }*/
                if (prefixGTS.length() != prefixGTS.lastIndexOf(".")) {
                    fix = ".";
                }
                String string = timestamp + "/" + location.getLatitude() + ":" + location.getLongitude() + "/ "
                        + prefixGTS + fix + location.getProvider() + "{" + "source=android" + "} true";
                stringBuffer.append(string);
                //Log.d("Location Handler", stringBuffer.toString());
            }
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
            emptyBuffer();
        }

        /**
         * empty current buffer
         */
        public void emptyBuffer() {
            if (null != stringBuffer) {
                //Log.d("LocationService", stringBuffer.toString());
                final StringBuffer buffer = new StringBuffer(stringBuffer);
                if (CollectService.isPostActive) {
                    FileService.writeToFile(buffer.toString(), context);
                } else {
                    if (CollectService.ws.isClosed()) {
                        FileService.writeToFile(buffer.toString(), context);
                    } else {
                        List<File> allFiles = FileService.getAllFiles("fill", context, true);
                        for (File file : allFiles) {
                            String data = FileService.readMetricFile(file);
                            if (CollectService.ws.writeData(data)) {
                                file.delete();
                            }
                        }
                        if (!CollectService.ws.writeData(buffer.toString())) {
                            FileService.writeToFile(buffer.toString(), context);
                        }
                    }
                }
                stringBuffer = new StringBuffer();
            }
        }
    };

    // Register the listener with the Location Manager to receive location updates
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    if (isListenGPS || recGPS) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    if (isListenNetWork || recNetwork) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    //Log.d("LOCATIONB", locationManager.getAllProviders().toString());
    //Log.d("LOCATIONB", locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).toString());
    isRunning = true;

}

From source file:de.grundid.plusrad.MainActivity.java

private void proccessWithLocationPermission() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();//w w  w.ja  va  2 s  . c o m
    } else {
        startActivity(new Intent(this, RecordingActivity.class));
    }
}

From source file:com.findcab.driver.activity.Signup.java

private boolean initGPS() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // GPS????/* w w w . ja v a 2 s .  c om*/
    if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "GPS is not open,Please open it!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 0);

        return false;
    } else {
        Toast.makeText(this, "GPS is ready", Toast.LENGTH_SHORT);
    }
    return true;
}

From source file:com.example.leandromaguna.myapp.Presentation.PlacesMap.PlacesMapActivity.java

/**
 * Enables the My Location layer if the fine location permission has been granted.
 *///  w  w w  .  ja  v  a2  s .  co m
private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission to access the location is missing.
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {

        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();
            return;
        }

        // Access to the location has been granted to the app.
        mMap.setMyLocationEnabled(true);
        //            mMap.setLocationSource(mLocationSource);
        //            mMap.setOnMapLongClickListener(mLocationSource);
        //
        Log.d(TAG, "enableMyLocation()");

        if (selectedLocation != null) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 15));
        }
    }
}

From source file:com.example.vedantn.algaeestimator.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

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

    //Set values for the main spinner
    calcMethodSpinner = (Spinner) findViewById(R.id.calcMethodSpinner);
    ArrayAdapter adapterCalcMethod = ArrayAdapter.createFromResource(this, R.array.calcMethod,
            android.R.layout.simple_spinner_dropdown_item);
    calcMethodSpinner.setAdapter(adapterCalcMethod);
    calcMethodSpinner.setOnItemSelectedListener(this);

    spinnerDepth = (Spinner) findViewById(R.id.spinnerDepth);
    spinnerDepth.setOnItemSelectedListener(this);

    spinnerStemp = (Spinner) findViewById(R.id.spinnerStemp);
    spinnerStemp.setOnItemSelectedListener(this);

    spinnerBotTemp = (Spinner) findViewById(R.id.spinnerBotTemp);
    spinnerBotTemp.setOnItemSelectedListener(this);

    spinnerSD = (Spinner) findViewById(R.id.spinnerSD);
    spinnerSD.setOnItemSelectedListener(this);

    //Get all user inputs
    tbValueOfAlgal = (EditText) findViewById(R.id.tbValueOfAlgal);
    tbPbott = (EditText) findViewById(R.id.tbPbott);
    tbDepth = (EditText) findViewById(R.id.tbDepth);
    tbStemp = (EditText) findViewById(R.id.tbStemp);
    tbBotTemp = (EditText) findViewById(R.id.tbBotTemp);
    tbSD = (EditText) findViewById(R.id.tbSD);
    tbDO = (EditText) findViewById(R.id.tbDO);
    tbLakeDescription = (EditText) findViewById(R.id.tbLakeDescription);
    lblLocation = (TextView) findViewById(R.id.lblLocation);
    //Get GPS coordinates
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {
        @Override//from w  w  w. j  a  v a 2 s. c  om
        //This methods is called every time the GPS location changes
        public void onLocationChanged(Location location) {

            if (location != null) {
                userLat = location.getLatitude();
                userLon = location.getLongitude();
                //Toast.makeText(MainActivity.this,"Location Changed",Toast.LENGTH_LONG).show();
                lblLocation.setText("Current Location\n" + userLat + "\n" + userLon);

            }

        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    //Get location updated after 60000 milliseconds or 5 meters.
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, locationListener);

}

From source file:com.kentli.cycletrack.RecordingService.java

public long finishRecording() {
    this.state = STATE_FULL;
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    lm.removeUpdates(this);

    clearNotifications();/* w  w w  . j av a2 s.c  o  m*/

    return trip.tripid;
}

From source file:com.johan.vertretungsplan_2.SelectSchoolActivity.java

private void showListGeo() {
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // no GPS
    final String provider = locationManager.getBestProvider(criteria, true);

    if (provider == null) {
        Log.d("vertretungsplan", "provider==null");
        tvLocateString.setText(R.string.geolocate_disabled);
        status = Status.LIST;/*from   w w w .  jav a 2  s.c  om*/
        return;
    }
    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!visible)
                return;
            if (location != null) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                for (Schule school : schools) {
                    float[] result = new float[1];
                    Location.distanceBetween(lat, lon, school.getGeo()[0], school.getGeo()[1], result);
                    school.setDistance(result[0]);
                    Log.d("vertretungsplan", school.getName() + ": " + school.getDistance());
                }
                Collections.sort(schools, new DistanceSchoolComparator());
                lstSchools.setAdapter(new SchoolsAdapter(SelectSchoolActivity.this, schools, true));
            }
            tvLocateString.setText(R.string.alphabetic_list);
            ivLocationIcon.setImageResource(R.drawable.ic_action_view_as_list);
            status = Status.GEO;
        }
    });
}