Example usage for android.location LocationManager NETWORK_PROVIDER

List of usage examples for android.location LocationManager NETWORK_PROVIDER

Introduction

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

Prototype

String NETWORK_PROVIDER

To view the source code for android.location LocationManager NETWORK_PROVIDER.

Click Source Link

Document

Name of the network location provider.

Usage

From source file:cordova.plugins.Diagnostic.java

/**
 * Returns current location mode//from   w  w  w.  j  a va2 s. c  o  m
 */
private int getLocationMode() throws Exception {
    int mode;
    if (Build.VERSION.SDK_INT >= 19) { // Kitkat and above
        mode = Settings.Secure.getInt(this.cordova.getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } else { // Pre-Kitkat
        if (isLocationProviderEnabled(LocationManager.GPS_PROVIDER)
                && isLocationProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            mode = 3;
        } else if (isLocationProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mode = 1;
        } else if (isLocationProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            mode = 2;
        } else {
            mode = 0;
        }
    }
    return mode;
}

From source file:uwp.cs.edu.parkingtracker.MainActivity.java

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    //status of gps changed
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
        actionBarMenu.findItem(R.id.action_park).setVisible(true);
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 1, this);
        actionBarMenu.findItem(R.id.action_park).setVisible(true);
    } else {//  www  . j ava  2 s  .  com
        //location is not working
        Toast.makeText(getApplicationContext(), "Please Check Location", Toast.LENGTH_LONG).show();
        actionBarMenu.findItem(R.id.action_park).setVisible(false);
    }
}

From source file:com.sitewhere.android.example.ExampleFragment.java

private boolean isLocationEnabled() {
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;//from   w  ww.ja  v a 2  s  . c om
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:org.noise_planet.noisecapture.MeasurementService.java

public void addLocation(Location location) {
    // Check if the previous location is inside the precision range of the new location
    // Keep the new location only if the new location is 60% chance away from previous location
    // and if the new location precision is at least with better accuracy and at most worst
    // than two times of old location
    // see https://developer.android.com/guide/topics/location/strategies.html
    Location previousLocation = timeLocation.isEmpty() ? null : timeLocation.lastEntry().getValue();
    if (previousLocation == null || (location.getProvider().equals(LocationManager.GPS_PROVIDER)
            || previousLocation.getProvider().equals(LocationManager.NETWORK_PROVIDER)
            || previousLocation.getProvider().equals(LocationManager.PASSIVE_PROVIDER))) {
        timeLocation.put(System.currentTimeMillis(), location);
        if (timeLocation.size() > MAXIMUM_LOCATION_HISTORY) {
            // Clean old entry
            timeLocation.remove(timeLocation.firstKey());
        }// w  w w . j a v  a 2 s .  c  o  m
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

protected void sendLocationMessage() {
    // TODO Auto-generated method stub
    if (checkGPSEnabled()) {
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }/*from   ww w . j av  a2s.  co  m*/

        if (location == null) {
            try {
                if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            } catch (Exception ex) {
            }
        }

        if (location != null) {
            String longitude = String.valueOf(location.getLongitude());
            String latitude = String.valueOf(location.getLatitude());
            String location_msg = "LOC-" + longitude + "-" + latitude;
            MessageFragment.sendImage(location_msg);
        } else {
            Toast.makeText(getApplicationContext(), "GPS is searching your coordinates. Please try again later",
                    Toast.LENGTH_SHORT).show();
        }

    } else {
        dialogBoxGPSDisabled();
    }
}

From source file:com.safecell.HomeScreenActivity.java

public void checkLocationProviderStatus() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        return; // We have GPS do nothing
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        showGPSStatusAlert(LocationManager.NETWORK_PROVIDER);
    } else {//from   w ww. j a  va  2  s  . c om
        showGPSStatusAlert(null);
    }
}

From source file:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*from  w  w w.j av  a2s.c o m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:com.google.android.gms.samples.vision.ocrreader.MainActivity.java

private void _getLocation() {
    // Get the location manager
    Coordinates = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET },
                PackageManager.PERMISSION_GRANTED);
    }//from  w w w.  j a  v  a 2 s  .  c o m

    GPSEnabled = true;
    NetworkEnabled = true;

    try {
        GPSEnabled = Coordinates.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }

    try {
        NetworkEnabled = Coordinates.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    if (!GPSEnabled) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is Required but Disabled : Enable GPS , Restart App.");

        alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                finish();
            }
        });

        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

    if (!NetworkEnabled) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Network is Required but Disabled : Enable Network , Restart App.");

        alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                finish();
            }
        });

        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    if (GPSEnabled && NetworkEnabled) {
        Coordinates.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });
        try {
            location = Coordinates.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            lat = location.getLatitude();
            lon = location.getLongitude();
        } catch (Exception e) {

        }
    }
}

From source file:com.safecell.HomeScreenActivity.java

public void showGPSStatusAlert(String provider) {

    // Log.v("Safecell", "" + provider);

    String title = "";
    String message = "";

    if (LocationManager.GPS_PROVIDER.equals(provider)) {
        return;/*w  ww. j a va  2  s  .c om*/
    }

    if (provider == null) {
        title = "GPS is not enabled.";
        message = "GPS is not enabled. Please enable it.";
    } else {
        title = "GPS is not enabled.";
        message = "GPS is not enabled. Please enable it. \nMeanwhile, background trip tracking will be disabled.";
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle(title);
    builder.setMessage(message);
    builder.setCancelable(false);

    builder.setPositiveButton("Launch Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            launchGPSOptions();
        }
    });

    if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
    }

    AlertDialog alert = builder.create();
    alert.show();
}