Example usage for android.location LocationListener LocationListener

List of usage examples for android.location LocationListener LocationListener

Introduction

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

Prototype

LocationListener

Source Link

Usage

From source file:com.nextgis.firereporter.SendReportActivity.java

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

    setContentView(R.layout.report);/*ww w  .j a va  2 s.c o m*/

    //add fragment
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    frCompass = (CompassFragment) getSupportFragmentManager().findFragmentByTag("COMPASS");
    if (frCompass == null) {
        frCompass = new CompassFragment();
        fragmentTransaction.add(R.id.compass_fragment_container, frCompass, "COMPASS").commit();
    }

    getSupportFragmentManager().executePendingTransactions();

    getSupportActionBar().setHomeButtonEnabled(true);

    edLatitude = (EditText) findViewById(R.id.edLatitude);
    edLongitude = (EditText) findViewById(R.id.edLongitude);
    edAzimuth = (EditText) findViewById(R.id.edAzimuth);
    edDistance = (EditText) findViewById(R.id.edDistance);
    edComment = (EditText) findViewById(R.id.edComment);

    edDistance.setText("100");

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (mLocationManager != null) {

        for (String aProvider : mLocationManager.getProviders(false)) {
            if (aProvider.equals(LocationManager.GPS_PROVIDER)) {
                gpsAvailable = true;
            }
        }

        if (gpsAvailable) {
            Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (location != null) {
                float lat = (float) (location.getLatitude());
                float lon = (float) (location.getLongitude());
                edLatitude.setText(Float.toString(lat));
                edLongitude.setText(Float.toString(lon));
            } else {
                edLatitude.setText(getString(R.string.noLocation));
                edLongitude.setText(getString(R.string.noLocation));
            }

            mLocationListener = new LocationListener() {
                public void onStatusChanged(String provider, int status, Bundle extras) {
                    switch (status) {
                    case LocationProvider.OUT_OF_SERVICE:
                        break;
                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        break;
                    case LocationProvider.AVAILABLE:
                        break;
                    }
                }

                public void onProviderEnabled(String provider) {
                }

                public void onProviderDisabled(String provider) {
                }

                public void onLocationChanged(Location location) {
                    float lat = (float) (location.getLatitude());
                    float lon = (float) (location.getLongitude());
                    edLatitude.setText(Float.toString(lat));
                    edLongitude.setText(Float.toString(lon));

                    // FIXME: also need to calculate declination?
                }
            }; // location listener
        } else {
            edLatitude.setText(getString(R.string.noGPS));
            edLongitude.setText(getString(R.string.noGPS));
            edLatitude.setEnabled(false);
            edLongitude.setEnabled(false);
        }
    }

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    boolean accelerometerAvailable = false;
    boolean magnetometerAvailable = false;
    for (Sensor aSensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) {
        if (aSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            accelerometerAvailable = true;
        } else if (aSensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            magnetometerAvailable = true;
        }
    }

    compassAvailable = accelerometerAvailable && magnetometerAvailable;
    if (compassAvailable) {
        //frCompass = (CompassFragment) getSupportFragmentManager().findFragmentByTag("COMPASS");
        if (frCompass != null) {
            frCompass.SetAzimuthCtrl(edAzimuth);
        }
    } else {
        edAzimuth.setText(getString(R.string.noCompass));
        edAzimuth.setEnabled(false);
    }
}

From source file:com.wikitude.samples.AbstractArchitectCamFragmentV4.java

@SuppressLint("NewApi")
@Override//from  w w w .  jav a2s.  co m
public void onActivityCreated(final Bundle bundle) {
    super.onActivityCreated(bundle);

    // set architectView, important for upcoming lifecycle calls
    this.architectView = (ArchitectView) this.getView().findViewById(getArchitectViewId());

    // pass license key to architectView while creating it
    final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
    config.setLicenseKey(this.getWikitudeSDKLicenseKey());
    config.setFeatures(ArchitectView.getSupportedFeaturesForDevice(getActivity()));
    config.setCameraResolution(CameraSettings.CameraResolution.SD_640x480);

    // forwards mandatory life-cycle-events, unfortunately there is no onPostCreate() event in fragments so we have to call it that way
    try {
        /* first mandatory life-cycle notification */
        this.architectView.onCreate(config);
        this.architectView.onPostCreate();
    } catch (RuntimeException rex) {
        this.architectView = null;
        Toast.makeText(getActivity().getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT)
                .show();
        Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex);
    }

    /*  
     *   this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml
     *   If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse.
     *   You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place.
     *   Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (0 != (getActivity().getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
    }

    try {

        // load architectView's content
        this.architectView.load(this.getARchitectWorldPath());

        if (this.getInitialCullingDistanceMeters() != ArchitectViewHolderInterface.CULLING_DISTANCE_DEFAULT_METERS) {
            // set the culling distance - meaning: the maximum distance to render geo-content
            this.architectView.setCullingDistance(this.getInitialCullingDistanceMeters());
        }

    } catch (IOException e) {
        // unexpected, if error occurs here your path is invalid
        e.printStackTrace();
    }

    // listener passed over to locationProvider, any location update is handled here
    this.locationListener = 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(final Location location) {
            if (location != null) {
                AbstractArchitectCamFragmentV4.this.lastKnownLocaton = location;
                if (AbstractArchitectCamFragmentV4.this.architectView != null) {
                    // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                    if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) {
                        AbstractArchitectCamFragmentV4.this.architectView.setLocation(location.getLatitude(),
                                location.getLongitude(), location.getAltitude(), location.getAccuracy());
                    } else {
                        AbstractArchitectCamFragmentV4.this.architectView.setLocation(location.getLatitude(),
                                location.getLongitude(),
                                location.hasAccuracy() ? location.getAccuracy() : 1000);
                    }
                }
            }
        }
    };

    // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
    this.sensorAccuracyListener = this.getSensorAccuracyListener();

    // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
    this.urlListener = this.getUrlListener();

    // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
    if (this.urlListener != null) {
        this.architectView.registerUrlListener(this.getUrlListener());
    }

    // locationProvider used to fetch user position
    this.locationProvider = this.getLocationProvider(this.locationListener);

}

From source file:com.chalmers.schmaps.GoogleMapSearchLocation.java

/**
 * onCreate method for determining what the activity does on creation.
 * Sets the right view for the user and assigns fields used by the activity.
 *//*from   w  ww.  j av a2 s  .  c  o  m*/

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

    //initiate the variables used in this class
    assignInstances();
    //if there is an provider that provides an location ->continue
    if (location != null) {
        //get the latitude
        latitude = (int) (location.getLatitude() * CONVERTTOGEOPOINTVALUE);
        //get the longitude
        longitude = (int) (location.getLongitude() * CONVERTTOGEOPOINTVALUE);
        //greates an geopoint with our location
        ourLocation = new GeoPoint(latitude, longitude);

        mapcon = mapView.getController();
        mapcon.animateTo(ourLocation);
        //zoom level
        mapcon.setZoom(OVERVIEWZOOMVALUE);

        //creates a MapItemizedOverlay-object and adds it to the list mapOverlays
        overlayitemStudent = new OverlayItem(ourLocation, "Hey amigo", "This is your position!");
        mapItemizedStudent.addOverlay(overlayitemStudent);
        mapOverlays.add(mapItemizedStudent);
    }

    locationListener = new LocationListener() {
        /**
         * method is called when location is changed
         */
        public void onLocationChanged(Location loc) {
            //get the latitude
            latitude = (int) (location.getLatitude() * CONVERTTOGEOPOINTVALUE);
            //get the longitude
            longitude = (int) (location.getLongitude() * CONVERTTOGEOPOINTVALUE);
            //greates an geopoint with our location
            ourLocation = new GeoPoint(latitude, longitude);

            //creates a MapItemizedOverlay-object and adds it to the list mapOverlays
            overlayitemStudent = new OverlayItem(ourLocation, "Hey amigo", "This is your position!");
            mapItemizedStudent.addOverlay(overlayitemStudent);
            mapOverlays.add(mapItemizedStudent);
        }

        public void onProviderDisabled(String arg0) {

        }

        public void onProviderEnabled(String provider) {

        }

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

        }

    };
    //creates a SQLLite object
    search = new SearchSQL(GoogleMapSearchLocation.this);
    //creates an database
    search.createDatabase();
}

From source file:me.trashout.service.TrashHunterService.java

private void setupLocationListener() {

    trashHunterState = PreferencesHandler.getTrashHunterState(getBaseContext());
    Log.d("TrashHunter", "setupLocationListener: " + trashHunterState);

    if (trashHunterState != null && trashHunterState.isTrashHunterActive()) {

        stopSelfHandler.postDelayed(stopSelfRunable, trashHunterState.getTrashHunterRemainingTime());

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

        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                try {
                    makeUseOfNewLocation(new LatLng(location.getLatitude(), location.getLongitude()));
                } catch (IOException e) {
                    e.printStackTrace();
                }/*from   ww  w.j a  v  a2 s.c  om*/
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.d("TrashHunter", "onStatusChanged: provider = " + provider + ", status = " + status);
            }

            public void onProviderEnabled(String provider) {
                Log.d("TrashHunter", "onProviderEnabled: " + provider);
            }

            public void onProviderDisabled(String provider) {
                Log.d("TrashHunter", "onProviderDisabled: " + provider);
            }
        };

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                trashHunterState.getUpdateStatusTime(), 0, locationListener);
    } else {
        Toast.makeText(this, "Trash hunter not activate.", Toast.LENGTH_SHORT).show();
        this.stopSelf();
    }
}

From source file:at.kropf.curriculumvitae.augmented.AbstractArchitectCamActivity.java

/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override/*from ww  w  .j a  v a2s  . c  om*/
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* pressing volume up/down should cause music volume changes */
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    /* set samples content view */
    this.setContentView(this.getContentViewId());

    this.setTitle(this.getActivityTitle());

    /*  
     *   this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml
     *   If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse.
     *   You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place.
     *   Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
    }

    /* set AR-view for life-cycle notifications etc. */
    this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId());

    /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */
    final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(),
            this.getFeatures(), this.getCameraPosition());

    try {
        /* first mandatory life-cycle notification */
        this.architectView.onCreate(config);
    } catch (RuntimeException rex) {
        this.architectView = null;
        Toast.makeText(getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT).show();
        Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex);
    }

    // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
    this.sensorAccuracyListener = this.getSensorAccuracyListener();

    // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
    this.urlListener = this.getUrlListener();

    // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
    if (this.urlListener != null && this.architectView != null) {
        this.architectView.registerUrlListener(this.getUrlListener());
    }

    if (hasGeo()) {
        // listener passed over to locationProvider, any location update is handled here
        this.locationListener = 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(final Location location) {
                // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy
                if (location != null) {
                    // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project)
                    AbstractArchitectCamActivity.this.lastKnownLocaton = location;
                    if (AbstractArchitectCamActivity.this.architectView != null) {
                        // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                        if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(), location.getAltitude(), location.getAccuracy());
                        } else {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(),
                                    location.hasAccuracy() ? location.getAccuracy() : 1000);
                        }
                    }
                }
            }
        };

        // locationProvider used to fetch user position
        this.locationProvider = getLocationProvider(this.locationListener);
    } else {
        this.locationProvider = null;
        this.locationListener = null;
    }
}

From source file:com.wbrenna.gtfsoffline.MainActivity.java

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

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }/*w w w . ja  va2  s.com*/

    mProgress = (ProgressBar) findViewById(R.id.progress);

    //read in the preferences
    mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    Set<String> emptyString = new HashSet<String>();
    emptyString.clear();

    Set<String> initial_preferences = mPrefs.getStringSet(getString(R.string.pref_dbs), emptyString);
    mDBListPrefsOld = initial_preferences;

    //this is the list of currently checked databases
    String[] tmpDBActive = initial_preferences.toArray(new String[initial_preferences.size()]);

    //we have to be careful to exclude databases that aren't in our directory
    dbHelper = new DatabaseHelper(this);
    dbHelper.gatherFiles();
    mDBList = dbHelper.GetListofDB();
    List<String> workingDBList = new ArrayList<String>();

    for (int i = 0; i < tmpDBActive.length; i++) {
        if (mDBList.contains(tmpDBActive[i])) {
            workingDBList.add(tmpDBActive[i]);
        } else {
            initial_preferences.remove(tmpDBActive[i]);
        }
    }
    if (workingDBList.size() == 0) {
        mDBActive = null;
    } else {
        mDBActive = workingDBList.toArray(new String[workingDBList.size()]);
    }

    Editor prefsDBEditor = mPrefs.edit();
    prefsDBEditor.putStringSet(getString(R.string.pref_dbs), initial_preferences);
    prefsDBEditor.commit();

    //Set up the location management
    mLocationHelper = new LocationHelper(this);
    mLocation = mLocationHelper.startLocationManager();

    // Define a listener that responds to location updates
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (mLocationHelper.isBetterLocation(location, mLocation)) {
                mLocation = location;
                if (mLocation != null) {
                    //new ProcessBusStops().execute();
                    mSectionsPagerAdapter.notifyDataSetChanged();

                } else {
                    Toast.makeText(getBaseContext(), R.string.last_location_fix, Toast.LENGTH_LONG).show();
                    //Log.e(TAG, "No more location fixes ");
                }
            }
        }

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    //TODO: eventually add automated downloading of databases...

    // Create the adapter that will return a fragment for each of the
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

}

From source file:com.njlabs.amrita.aid.about.Amrita.java

public void directions_cbe(View view) {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;//from w  w  w  . ja  v a 2  s  .co m
    }

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }

        public void onProviderEnabled(String p) {
        }

        public void onProviderDisabled(String p) {
        }

        public void onStatusChanged(String p, int status, Bundle extras) {
        }
    };
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
    Uri uri = Uri.parse(
            "http://maps.google.com/maps?f=d&saddr=" + lat + "," + lon + "&daddr=10.900539,76.902806&hl=en");
    Intent it = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(it);

}

From source file:com.example.snapcacheexample.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//from w  w  w  .j  a v  a 2 s.  co m
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            float distance = location.distanceTo(placePickerFragment.getLocation());
                            if (distance >= LOCATION_CHANGE_THRESHOLD) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location == null) {
                String model = Build.MODEL;
                if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
                    // this may be the emulator, pretend we're in an exotic place
                    location = SAN_FRANCISCO_LOCATION;
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            } else {
                onError(getResources().getString(R.string.no_location_error), true);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.example.david.wheretogo_test1.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//from  ww  w . j a  v a  2  s.  c o  m
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location == null) {
                String model = Build.MODEL;
                if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
                    // this may be the emulator, pretend we're in an exotic place
                    location = SAN_FRANCISCO_LOCATION;
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            } else {
                onError(getResources().getString(R.string.no_location_error), true);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.company.millenium.iwannask.MainActivity.java

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

    //GPS//from w  ww .j a  v  a2  s .  co  m
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}