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.example.android.expandingcells.ExpandingCells.java

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

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default

    criteria.setCostAllowed(false);//from w w  w .  j a va  2s.  c om
    // get the best provider depending on the criteria
    provider = locationManager.getBestProvider(criteria, false);

    // the last known location of this provider
    Location location = locationManager.getLastKnownLocation(provider);

    mylistener = new MyLocationListener();

    if (location != null) {
        mylistener.onLocationChanged(location);
    } else {
        // leads to the settings because there is no last known location
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    // location updates: at least 1 meter and 200millsecs change
    //NETWORK_PROVIDER
    locationManager.requestLocationUpdates(provider, 200, 1, mylistener);

    this.NewsList = new ArrayList<News>(4);
    for (int i = 0; i < 4; i++) {
        NewsList.add(new News());
    }

    //Methods to populate the Object
    getColor();
    getHoroscope();
    getRaghukalam();
    //getWeather();

    //Log.d("DEBUG", Byte.getBody());
    Log.d("DEBUG", "Print");
    // Toast.makeText(this, Byte.size(), Toast.LENGTH_LONG).show();

    ExpandableListItem[] values = new ExpandableListItem[] {
            new ExpandableListItem("Color", R.drawable.mb_color, CELL_DEFAULT_HEIGHT,
                    NewsList.get(0).getBody()),
            new ExpandableListItem("Horoscope", R.drawable.mb_horoscope, CELL_DEFAULT_HEIGHT,
                    NewsList.get(1).getBody()),
            new ExpandableListItem("Raghukalam", R.drawable.mb_raghukalam, CELL_DEFAULT_HEIGHT,
                    NewsList.get(2).getBody()),
            new ExpandableListItem("Weather", R.drawable.mb_weather, CELL_DEFAULT_HEIGHT,
                    NewsList.get(3).getBody()), };

    List<ExpandableListItem> mData = new ArrayList<ExpandableListItem>();

    for (int i = 0; i < NUM_OF_CELLS; i++) {
        ExpandableListItem obj = values[i % values.length];
        mData.add(new ExpandableListItem(obj.getTitle(), obj.getImgResource(), obj.getCollapsedHeight(),
                obj.getText()));
    }

    // CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.list_view_item, mData);
    adapter = new CustomArrayAdapter(this, R.layout.list_view_item, mData);

    mListView = (ExpandingListView) findViewById(R.id.main_list_view);
    mListView.setAdapter(adapter);
    mListView.setDivider(null);
}

From source file:com.boundlessgeo.spatialconnect.scutilities.LocationHelper.java

public LocationHelper(Context context, GoogleMap map) {
    this.context = context;
    this.map = map;
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

From source file:com.dotd.mgrs.gps.MGRSLocationListener.java

public int onStartCommand(Intent intent, int flags, int startId) {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    sendMessageBroadcast(getString(R.string.acquiring));

    return Service.START_NOT_STICKY;
}

From source file:com.yammy.meter.map.MainMapBengkel.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.isvo_map_bengkel);
    this.jarak = (TextView) this.findViewById(R.id.map_bengkel_length);

    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
    if (result != ConnectionResult.SUCCESS) {
        GooglePlayServicesUtil.getErrorDialog(result, MainMapBengkel.this, 1).show();
    } else {//from   ww  w.j  a  va2 s.c o  m
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getBaseContext());

        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.setIndoorEnabled(false);
        bundle = getIntent().getExtras();
        try {
            data_pos = new LatLng(Double.parseDouble(bundle.getString("lat")),
                    Double.parseDouble(bundle.getString("long")));
            Toast.makeText(getBaseContext(), bundle.getString("lat") + "," + bundle.getString("long"),
                    Toast.LENGTH_LONG).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getBaseContext(), "Mencari lokasi saat ini", Toast.LENGTH_SHORT).show();
        }

        /**
         * mulai edan dari ini ke bawah
         */
        LocationManager service = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!enabledGPS) {
            Toast.makeText(this, "GPS tidak ditemukan", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this);
        if (location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
            Toast.makeText(getApplicationContext(),
                    "Current Location : " + location.getLatitude() + "," + location.getLongitude(),
                    Toast.LENGTH_LONG).show();
            drawMarker(location);
        } else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
    }
}

From source file:com.itsherpa.andg.ui.LocationFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}

From source file:com.ushahidi.android.app.activities.BaseMapActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (layout != 0) {
        setContentView(layout);/* ww w. j a  v a  2  s . co m*/

    }
    if (mapViewId != 0) {
        mapView = (MapView) findViewById(mapViewId);
        super.mapView = mapView;
    }
    if (locationManager == null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    view = Objects.createInstance(viewClass, Activity.class, this);
}

From source file:com.clevertrail.mobile.findtrail.Activity_FindTrail_ByLocation.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //prevent automatic popup of soft keyboard
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    //register the listener with the Location Manager to receive location updates
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    //set the title bar
    TitleBar.setCustomTitleBar(this, R.layout.findtrail_bylocation, getString(R.string.title_findtrails),
            R.drawable.ic_viewtrailtab_map_unselected);

    mActivity = this;

    //create the search proximity combo box
    createProximityComboBox();/* w  ww .  j  a  v a  2s  .  com*/

    //register radio button events
    RadioButton rbCity = (RadioButton) findViewById(R.id.rbFindTrailByLocationCity);
    rbCity.setOnClickListener(onclickRBCity);

    RadioButton rbProximity = (RadioButton) findViewById(R.id.rbFindTrailByLocationProximity);
    rbProximity.setOnClickListener(onclickRBProximity);

    Button btnSearch = (Button) findViewById(R.id.btnSearchByLocation);
    btnSearch.setOnClickListener(onclickSearch);
}

From source file:ca.mudar.mtlaucasou.LocationFragmentActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAppHelper = (AppHelper) getApplicationContext();
    mActivityHelper = ActivityHelper.createInstance(this);

    prefs = getSharedPreferences(Const.APP_PREFS_NAME, Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();/* w w  w .  j av  a 2 s. com*/

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

    /**
     * Instantiate a LastLocationFinder class. This will be used to find the
     * last known location when the application starts.
     */
    lastLocationFinder = PlatformSpecificImplementationFactory.getLastLocationFinder(this);
    lastLocationFinder.setChangedLocationListener(oneShotLastLocationUpdateListener);
    hasRegisteredSingleUpdateReceiver = true;

    /**
     * Set the last known location as user's current location.
     */
    mAppHelper.setLocation(lastLocationFinder.getLastBestLocation(Const.MAX_DISTANCE, Const.MAX_TIME));

    /**
     * Specify the Criteria to use when requesting location updates while
     * the application is Active.
     */
    criteria = new Criteria();
    if (Const.USE_GPS_WHEN_ACTIVITY_VISIBLE) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setPowerRequirement(Criteria.POWER_LOW);
    }

    /**
     * Setup the location update Pending Intents.
     */
    Intent activeIntent = new Intent(this, LocationChangedReceiver.class);
    locationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent passiveIntent = new Intent(this, PassiveLocationChangedReceiver.class);
    locationListenerPassivePendingIntent = PendingIntent.getBroadcast(this, 0, passiveIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    locationManager.removeUpdates(locationListenerPassivePendingIntent);

    /**
     * Instantiate a Location Update Requester class based on the available
     * platform version. This will be used to request location updates.
     */
    locationUpdateRequester = PlatformSpecificImplementationFactory
            .getLocationUpdateRequester(this.getApplicationContext(), locationManager);

    super.onCreate(savedInstanceState);
}

From source file:com.nearnotes.NoteLocation.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    Bundle extras = getArguments();//from ww w  . ja v  a  2 s.c o  m
    mTypeFrag = extras.getInt("TypeFrag");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Boolean gpsPref = sharedPref.getBoolean("pref_key_ignore_gps", false);
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    mCriteria = new Criteria();
    if (gpsPref) {
        mCriteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else
        mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    boolean oldApi = false;
    int locationMode = 4;
    Log.e("mProvider", mProvider);

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean networkAvailable = true;

    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    boolean networkType = true;
    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected()) {
        networkType = false;
    }

    Log.d("Phone state before if statement", "Phone State: " + mServiceState);
    Log.e("network isavailable", String.valueOf(networkInfo.isAvailable()));
    if (!networkType || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    try {
        Log.e("Location_mode", String.valueOf(
                Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE)));
        locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } catch (SettingNotFoundException e) {
        oldApi = true;
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if ((oldApi && mProvider.matches("passive")) || locationMode == LOCATION_MODE_OFF || (!networkAvailable
            && (mProvider.matches("network") || (!gpsPref && mProvider.matches("gps"))))) {
        builder.setTitle(getString(R.string.dialog_location_no_location_services_title));
        builder.setMessage(getString(R.string.dialog_location_no_location_services_message));
        builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);
        mAbortRequest = true;
    } else if ((oldApi && mProvider.matches("gps") && gpsPref) || (mProvider.matches("gps") && gpsPref
            && (locationMode == LOCATION_MODE_SENSORS_ONLY || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_gps));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_gps));
        }
        if (locationMode == LOCATION_MODE_SENSORS_ONLY || (oldApi && mProvider.matches("gps"))
                || !networkAvailable) {
            builder.setMessage(getString(R.string.dialog_location_only_gps_message));
            builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);

        } else
            builder.setPositiveButton(R.string.dialog_location_use_network, null);

        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));

    } else if ((oldApi && mProvider.matches("network")) || (mProvider.matches("network")
            && (locationMode == LOCATION_MODE_BATTERY_SAVING || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_network));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_network));
        }

    }
    builder.setNegativeButton(R.string.cancel, cancelListener);
    // Create the AlertDialog object and return it

    // builder.create();

    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mTypeFrag);
                mLocationManager.removeUpdates(NoteLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }

            return false;
        }
    });

    mRealDialog = builder.create();
    // final LocationListener getFragment() = this.;

    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    // mRealDialog.setCancelable(false);
    return mRealDialog;

}

From source file:com.initiativaromania.hartabanilorpublici.IRUserInterface.map.IRLocationListener.java

/**
 * Resume location setup after permissions have been granted
 *///from   w  w w .j a v  a  2 s.c o  m
public void setupLocation(boolean onResume) {
    this.locationManager = (LocationManager) act.getSystemService(Context.LOCATION_SERVICE);

    // Get GPS and network status
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (forceNetwork)
        isGPSEnabled = false;

    if (!isNetworkEnabled && !isGPSEnabled) {
        System.out.println("Cannot get loc");
        return;
    }

    System.out.println("Can get loc");

    try {
        if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            if (onResume == false && locationManager != null) {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                act.setInitialPosition(location);
            }
        } //end if

        if (isGPSEnabled) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

            if (onResume == false && locationManager != null) {
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                act.setInitialPosition(location);
            }
        }
    } catch (SecurityException se) {
        System.out.println("Unable to resume location setup");
    }
}