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.temboo.example.FoursquareConnectedActivity.java

/**
 * onCreate is called by Android when the activity is first created.
 *///from w  w  w.  j av a2  s. com
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Initialize the UI with the "connected mode" layout (defined in /res/layout/foursquare_connected.xml)
    setContentView(R.layout.foursquare_connected);

    // Obtain a reference to the "current venue" textview
    currentVenueTextView = (TextView) findViewById(R.id.foursquareVenueField);

    // Initiate the Temboo session
    try {
        session = new MyTemboo(TEMBOO_APPKEY_NAME, TEMBOO_APPKEY);
    } catch (Exception e) {
        currentVenueTextView.setText("Uh-oh! Something has gone horribly wrong.");
        Log.e("TEMBOO", "Error starting Temboo session.", e);
    }

    // Debug: display the Fourquare Oauth token retrieved by FoursquareOauthActivity
    Toast.makeText(FoursquareConnectedActivity.this,
            "Successfully connected to Foursquare. Oauth token: " + FOURSQUARE_OAUTH_TOKEN, Toast.LENGTH_SHORT)
            .show();

    // Obtain a reference to the Android LocationManager, which is (surprisingly) responsible for managing GPS/location data
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Get and store the last known location
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // Register a listener with the Location Manager to receive location updates. Currently, this is configured
    // to request GPS updates every 3 minutes, with a minimum location-differential of 3 meters per update. 
    // See http://developer.android.com/reference/android/location/LocationManager.html
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 180000, 3, new LocationListener() {

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        // When the location changes, store the current location in the parent activity
        @Override
        public void onLocationChanged(Location location) {
            currentLocation = location;
        }
    });

    // Attach the "lookup location" button click handler
    Button lookupButton = (Button) findViewById(R.id.getVenue);
    lookupButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                getFoursquareVenueForCurrentLocation();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare venue lookup", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare venue lookup! " + e.getMessage(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    // Attach the "Foursquare checkin" button click handler
    Button checkinButton = (Button) findViewById(R.id.doFoursquareCheckin);
    checkinButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                doFoursquareCheckin();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare checkin", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare checkin! " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recording);//from  w w  w.  j a v a2s  .c  o  m
    initWidget();

    if (rService == null)
        rService = new Intent(RecordingActivity.this, RecordingService.class);
    startService(rService);

    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            recordService = rs;

            int state = rs.getState();
            updateUIAccordingToState(rs.getState());
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(RecordingActivity.this, SaveTrip.class));
                } else {
                    if (state == RecordingService.STATE_RECORDING) {
                        isRecording = true;
                        initTrip();
                    }
                    //PAUSE or RECORDING...
                    recordService.setListener(RecordingActivity.this);
                }
            } else {
                //  First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                }
            }
            RecordingActivity.this.unbindService(this); // race?  this says we no longer care

            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            }
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    //Google Map
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    setButtonOnClickListeners();

}

From source file:it.unipr.informatica.autobusparma.MappaFragment.java

public Location getLocation(long MIN_DISTANCE, long MIN_TIME) {
    Location location = null;/*from  w ww . j a v a2  s  .c  o m*/
    try {
        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        // getting GPS status e network
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE,
                        this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE,
                            this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

From source file:com.example.isse.weatherapp.ui.WeatherListActivity.java

public void startLocationDetection() {
    this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (checkPermission()) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME_UPDATES, DISTANCE_UPDATES,
                this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, TIME_UPDATES, DISTANCE_UPDATES,
                this);
        Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Location location = gpsLocation != null ? gpsLocation : networkLocation;
        Log.v("create", "location(" + location + ")");
    }/*from  w w  w.  jav  a 2 s  .  c om*/
}

From source file:com.uproot.trackme.LocationActivity.java

@Override
protected void onStart() {
    super.onStart();

    // Check if the GPS setting is currently enabled on the device.
    // This verification should be done during onStart() because the system
    // calls this method
    // when the user returns to the activity, which ensures the desired
    // location provider is
    // enabled each time the activity resumes from the stopped state.
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!gpsEnabled) {
        // Build an alert dialog here that requests that the user enable
        // the location services, then when the user clicks the "OK" button,
        // call enableLocationSettings()
        new EnableGpsDialogFragment().show(getSupportFragmentManager(), "enableGpsDialog");
    }//from   w  w  w.  j av  a  2 s . com
    setup();
}

From source file:com.rareventure.gps2.reviewer.map.OsmMapGpsTrailerReviewerMapActivity.java

@Override
public void doOnCreate(Bundle savedInstanceState) {
    super.doOnCreate(savedInstanceState);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    ContextCompat.startForegroundService(this, new Intent(this, GpsTrailerService.class));

    timeAndDateSdf = new SimpleDateFormat(getString(R.string.time_and_date_format));

    GTG.cacheCreatorLock.registerReadingThread();
    try {//from w  w w .ja  v a 2  s .c  om
        /* ttt_installer:remove_line */Log.d(GTG.TAG, "OsmMapGpsTrailerReviewerMapActivity.onCreate()");

        //sometimes onDestroy forgets to be called, so we need to check for this and cleanup after the last instance
        if (reviewerStillRunning) {
            Log.w(GTG.TAG, "OsmMapGpsTrailerReviewerMapActivity: onDestroy() forgot to be called!");
            cleanup();
        }

        reviewerStillRunning = true;

        setContentView(R.layout.osm_gps_trailer_reviewer);

        osmMapView = (OsmMapView) findViewById(R.id.osmmapview);
        osmMapView.onCreate(savedInstanceState);

        initUI();

        ViewTreeObserver vto = this.findViewById(android.R.id.content).getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                initWithWorkingGetWidth();
                findViewById(android.R.id.content).getViewTreeObserver().removeGlobalOnLayoutListener(this);
                osmMapView.initAfterLayout();
            }
        });
    } finally {
        GTG.cacheCreatorLock.unregisterReadingThread();
    }
}

From source file:be.brunoparmentier.openbikesharing.app.activities.MapActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_my_location:
        try {/*from   w  w w . j  ava 2s. c  om*/
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            GeoPoint userLocation = new GeoPoint(
                    locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
            mapController.animateTo(userLocation);
            return true;
        } catch (NullPointerException ex) {
            Toast.makeText(this, getString(R.string.location_not_found), Toast.LENGTH_LONG).show();
            Log.e(TAG, "Location not found");
            return true;
        }
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.hfoss.posit.android.functionplugin.reminder.SetReminder.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the transparent blank screen as a background for dialogs
    setContentView(R.layout.blank_screen);

    // Exit the Activity if the proper settings are not enabled
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean allowReminder = prefs.getBoolean("allowReminderKey", true);
    boolean allowGeoTag = prefs.getBoolean("geotagKey", true);
    // If the user allows, set the "Set Reminder" menu option
    if (!allowReminder || !allowGeoTag) {
        Toast.makeText(this, "Sorry. Geotagging and Allow Reminder settings must "
                + " be enabled to run the Set Reminder Activity.", Toast.LENGTH_LONG).show();
        finish();/*from w  ww.ja va 2s . c om*/
    }

    mDbEntries = getIntent().getParcelableExtra("DbEntries");

    dateSetPressed = false;

    // Get intent passed in from FindActivity
    Bundle bundle = getIntent().getExtras();
    date = bundle.getString("Date");

    // Initialize variables for Date Picker Dialog
    year = date.substring(0, 4);
    month = date.substring(5, 7);
    day = date.substring(8, 10);

    // Initialize variables for longitude and latitude      
    findsLongitude = bundle.getDouble("FindsLongitude");
    findsLatitude = bundle.getDouble("FindsLatitude");

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Location netLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    Location gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Location loc = null;

    if (gpsLocation != null) {
        loc = gpsLocation;
    } else {
        loc = netLocation;
    }
    if (loc != null) {
        currentLongitude = loc.getLongitude();
        currentLatitude = loc.getLatitude();
    }

    showDatePickerDialog();
}

From source file:com.android.jhansi.designchallenge.MapFragment.java

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location location = null;/*w w  w  .j  a v  a 2  s.c  o m*/
    if (ActivityCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            //} else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    MY_PERMISSION_ACCESS_FINE_LOCATION);
        }
    } else {
        LocationManager mLocationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    }

    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    } else {
        handleNewLocation(location);
    }

}

From source file:com.example.ogadrive.HomeActivity2.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home2);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    mToolbar.setNavigationIcon(R.drawable.home);
    //mToolbar.setLogo(R.drawable.ic_launcher);

    setSupportActionBar(mToolbar);//from  w ww. j a  va  2 s .c o m

    bundle = getIntent().getExtras();
    User user = (User) bundle.getSerializable("User");

    setUser(user);
    mTitle = mDrawerTitle = getTitle();
    //      mPlanetTitles = getResources()
    //            .getStringArray(R.array.Oga_options_array);

    mPlanetTitles = new String[] {
            "" + user.getName() + System.getProperty("line.separator") + "" + user.getPhone(), "Home",
            "Book Vehicle", "History", "Emergency Contact", "Support", "About" };

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer
    // opens
    // mDrawerLayout.setDrawerShadow(R.drawable.ic_launcher,
    // GravityCompat.START);
    // set up the drawer's list view with items and click listener
    /*mDrawerList.setAdapter(new ArrayAdapter<String>(this,
    R.layout.drawer_list_item, mPlanetTitles));*/

    mDrawerList.setAdapter(new NavigationAdapter(this, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_launcher, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(1);
    }

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

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

    Intent intentLocationSerVice = new Intent(this, com.example.services.LocationUpdateService_2.class);
    LocationUpdateService_2.token = user.getToken();
    startService(intentLocationSerVice);
}