Example usage for android.location LocationManager getLastKnownLocation

List of usage examples for android.location LocationManager getLastKnownLocation

Introduction

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

Prototype

@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public Location getLastKnownLocation(String provider) 

Source Link

Document

Returns a Location indicating the data from the last known location fix obtained from the given provider.

Usage

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*w ww .  j a  va 2 s  .com*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION, false);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != 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();//  w  w  w  . j a  va 2s.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:org.mariotaku.twidere.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *///from ww w.  j av  a2 s .  co m
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:com.example.angel.parkpanda.MainActivity.java

public Location getLocation() {
    Location location = null;/*from   w ww.  j  ava 2s. co  m*/
    LocationManager locationManager;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    double longitude, latitude;
    long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    try {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (isNetworkEnabled) {
                if (ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return null;
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    return location;
}

From source file:com.androzic.Androzic.java

/**
 * Retrieves last known location without enabling location providers.
 * @return Most precise last known location or null if it is not available
 *///w w  w . j  av  a  2  s  .c o m
public Location getLastKnownSystemLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);
    Location l = null;

    for (int i = providers.size() - 1; i >= 0; i--) {
        l = lm.getLastKnownLocation(providers.get(i));
        if (l != null)
            break;
    }

    return l;
}

From source file:net.jongrakko.zipsuri.activity.PostUploadActivity.java

@Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
    if (isChecked) {
        switch (buttonView.getId()) {
        case R.id.radioButtonAddressGPS:
            mEditTextAddress.setOnClickListener(null);
            this.mGoogleMap.setOnMapClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(this);

            if (ContextCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mGoogleMap.setMyLocationEnabled(true);
                LocationProvider lprovider;
                LocationManager lm = (LocationManager) getActivity()
                        .getSystemService(getActivity().LOCATION_SERVICE);
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                String provider;/*from  ww w .j a  v  a  2 s .co  m*/
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setPowerRequirement(Criteria.POWER_HIGH);
                provider = lm.getBestProvider(criteria, true);

                if (provider == null || provider.equals("passive")) { // ? ?    ??
                    new AlertDialog.Builder(getActivity()).setTitle(" ??")
                            .setNeutralButton("??", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    buttonView.toggle();
                                    startActivityForResult(
                                            new Intent(
                                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                                            0);
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    dialog.dismiss();
                                }
                            }).show();
                } else { //  ? ?   
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
                    Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (l != null) {
                        Log.e("hello??", "okok");
                    }
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                            MY_LOCATION_REQUEST_CODE);
                }
            }
            break;
        case R.id.radioButtonAddressSelf:
            this.mGoogleMap.setOnMapClickListener(null);
            mEditTextAddress.setOnClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(null);
            mGoogleMap.setMyLocationEnabled(false);
            mEditTextAddress.setOnClickListener(this);
            startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS);
            break;
        }
    }
}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    //        final View v = inflater.inflate(R.layout.fragment_overview, null);
    View v = null;//  w w  w. j av a  2 s . com

    v = inflater.inflate(R.layout.fragment_main, container, false);

    //        stepsView = (TextView) v.findViewById(R.id.steps);
    //        totalView = (TextView) v.findViewById(R.id.total);
    totalView = (TextView) v.findViewById(R.id.tv_distance);
    tv_avg = (TextView) v.findViewById(R.id.tv_avg);
    tv_max = (TextView) v.findViewById(R.id.tv_max);
    tv_min = (TextView) v.findViewById(R.id.tv_min);
    //        averageView = (TextView) v.findViewById(R.id.average);

    /*
            pg = (PieChart) v.findViewById(R.id.graph);
            
            // slice for the steps taken today
            sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00"));
            pg.addPieSlice(sliceCurrent);
            
            // slice for the "missing" steps until reaching the goal
            sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000"));
            pg.addPieSlice(sliceGoal);
            
            pg.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View view) {
        showSteps = !showSteps;
        stepsDistanceChanged();
    }
            });
            
            pg.setDrawValueInPie(false);
            pg.setUsePieRotation(true);
            pg.startAnimation();
    */

    /*
    * MainActivity
    * */
    // Always cast your custom Toolbar here, and set it as the ActionBar.
    Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(tb);

    TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center);
    tv_tb_center.setText("ALPHA FITNESS");

    /*   ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart);
       imgbtn_cart.setVisibility(View.GONE);*/

    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });

    // Get the ActionBar here to configure the way it behaves.
    final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
    //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button
    ab.setDisplayShowHomeEnabled(false); // show or hide the default home button
    ab.setDisplayHomeAsUpEnabled(false);
    ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout
    ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title)

    tv_duration = (TextView) v.findViewById(R.id.tv_duration);

    startButton = (Button) v.findViewById(R.id.btn_start);
    if (isButtonStartPressed) {
        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            onSWatchStart();
        }
    });
    iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Database db = Database.getInstance(getActivity());
            tot_workouts = db.getTotWorkouts();
            tot_workTime = db.getWorkTime();
            Log.e("Tot Work time", tot_workTime + "");
            //                int seconds = (int) (tot_workTime / 1000) % 60;
            //                int minutes = (int) ((tot_workTime / (1000 * 60)) % 60);

            long millis = tot_workTime * 100; // obtained from StopWatch
            long hours = (millis / 1000) / 3600;
            long minutes = (millis / 1000) / 60;
            long seconds = (millis / 1000) % 60;

            db.close();

            Intent i = new Intent(getActivity(), ProfileActivity.class);
            i.putExtra("avg_distance", avg_distance + "");
            i.putExtra("all_distance", all_distance + "");
            i.putExtra("avg_time", tv_duration.getText().toString());
            i.putExtra("all_time", tv_duration.getText().toString());
            i.putExtra("avg_calories", avg_calories + "");
            i.putExtra("all_calories", all_calories + "");
            i.putExtra("tot_workouts", tot_workouts + "");
            i.putExtra("avg_workouts", tot_workouts + "");

            i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec");

            startActivity(i);

        }
    });

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        //            SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
        MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        mGoogleMap = fm.getMap();

        // Enable MyLocation Button in the Map
        mGoogleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location;
        if (provider != null) {

            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            location = locationManager.getLastKnownLocation(provider);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else {
            location = new Location("");
            location.setLatitude(0.0d);//your coords of course
            location.setLongitude(0.0d);
        }

        if (location != null) {
            onLocationChanged(location);
        }

        // Setting onclick event listener for the map
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if (mMarkerPoints.size() > 1) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    mMarkerPoints.clear();
                    mGoogleMap.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);
                    drawMarker(startPoint);
                }

                drawMarker(point);

                // Checks, whether start and end locations are captured
                if (mMarkerPoints.size() >= 2) {
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }
            }
        });
        fixedCentreoption = new MarkerOptions();

        mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                // TODO Auto-generated method stub
                // Get the center of the Map.

                mGoogleMap.clear();

                LatLng centerOfMap = mGoogleMap.getCameraPosition().target;

                // Update your Marker's position to the center of the Map.
                fixedCentreoption.position(centerOfMap);
                //                   mGoogleMap.addMarker(fixedCentreoption);
                //                   drawMarker(centerOfMap);
                LatLng origin = new LatLng(0.0d, 0.0d);
                ;
                if (mMarkerPoints.size() > 0) {
                    origin = mMarkerPoints.get(0);
                }
                //                  LatLng dest = mMarkerPoints.get(1);
                LatLng dest = centerOfMap;
                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);

                GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext());
                //               String Addrs = gpsTracker.location();
                Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap);
                //               Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show();

            }
        });
    }

    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "50"));

    return v;
}

From source file:org.telegram.ui.ThemeActivity.java

private void updateSunTime(Location lastKnownLocation, boolean forceUpdate) {
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            if (activity.checkSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION }, 2);
                return;
            }/*  ww  w . j av a 2s.  c o m*/
        }
    }
    if (getParentActivity() != null) {
        if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
            return;
        }
        try {
            LocationManager lm = (LocationManager) ApplicationLoader.applicationContext
                    .getSystemService(Context.LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("GpsDisabledAlert", R.string.GpsDisabledAlert));
                builder.setPositiveButton(
                        LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable),
                        (dialog, id) -> {
                            if (getParentActivity() == null) {
                                return;
                            }
                            try {
                                getParentActivity().startActivity(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            } catch (Exception ignore) {

                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
                return;
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    try {
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    if (lastKnownLocation == null || forceUpdate) {
        startLocationUpdate();
        if (lastKnownLocation == null) {
            return;
        }
    }
    Theme.autoNightLocationLatitude = lastKnownLocation.getLatitude();
    Theme.autoNightLocationLongitude = lastKnownLocation.getLongitude();
    int time[] = SunDate.calculateSunriseSunset(Theme.autoNightLocationLatitude,
            Theme.autoNightLocationLongitude);
    Theme.autoNightSunriseTime = time[0];
    Theme.autoNightSunsetTime = time[1];
    Theme.autoNightCityName = null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    Theme.autoNightLastSunCheckDay = calendar.get(Calendar.DAY_OF_MONTH);
    Utilities.globalQueue.postRunnable(() -> {
        String name;
        try {
            Geocoder gcd = new Geocoder(ApplicationLoader.applicationContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(Theme.autoNightLocationLatitude,
                    Theme.autoNightLocationLongitude, 1);
            if (addresses.size() > 0) {
                name = addresses.get(0).getLocality();
            } else {
                name = null;
            }
        } catch (Exception ignore) {
            name = null;
        }
        final String nameFinal = name;
        AndroidUtilities.runOnUIThread(() -> {
            Theme.autoNightCityName = nameFinal;
            if (Theme.autoNightCityName == null) {
                Theme.autoNightCityName = String.format("(%.06f, %.06f)", Theme.autoNightLocationLatitude,
                        Theme.autoNightLocationLongitude);
            }
            Theme.saveAutoNightThemeConfig();
            if (listView != null) {
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
                        .findViewHolderForAdapterPosition(scheduleUpdateLocationRow);
                if (holder != null && holder.itemView instanceof TextSettingsCell) {
                    ((TextSettingsCell) holder.itemView).setTextAndValue(LocaleController
                            .getString("AutoNightUpdateLocation", R.string.AutoNightUpdateLocation),
                            Theme.autoNightCityName, false);
                }
            }
        });
    });
    RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
            .findViewHolderForAdapterPosition(scheduleLocationInfoRow);
    if (holder != null && holder.itemView instanceof TextInfoPrivacyCell) {
        ((TextInfoPrivacyCell) holder.itemView).setText(getLocationSunString());
    }
    if (Theme.autoNightScheduleByLocation && Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
        Theme.checkAutoNightThemeConditions();
    }
}

From source file:plugin.google.maps.GoogleMaps.java

@SuppressWarnings("unused")
private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {

    LocationManager locationManager = (LocationManager) this.activity
            .getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    if (providers.size() == 0) {
        JSONObject result = new JSONObject();
        result.put("status", false);
        result.put("error_code", "not_available");
        result.put("error_message",
                "Since this device does not have any location provider, this app can not detect your location.");
        callbackContext.error(result);//from  ww  w.  j  ava2 s.  com
        return;
    }

    // enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY
    // enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY

    JSONObject params = args.getJSONObject(0);
    boolean isHigh = false;
    if (params.has("enableHighAccuracy")) {
        isHigh = params.getBoolean("enableHighAccuracy");
    }
    final boolean enableHighAccuracy = isHigh;

    String provider = null;
    if (enableHighAccuracy == true) {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        }
    } else {
        if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        }
    }
    if (provider == null) {
        //Ask the user to turn on the location services.
        AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
        builder.setTitle("Improve location accuracy");
        builder.setMessage("To enhance your Maps experience:\n\n" + " - Enable Google apps location access\n\n"
                + " - Turn on GPS and mobile network location");
        builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Launch settings, allowing user to make a change
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activity.startActivity(intent);

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "open_settings");
                    result.put("error_message", "User opened the settings of location service. So try again.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //No location service, no Activity
                dialog.dismiss();

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "service_denied");
                    result.put("error_message", "This app has rejected to use Location Services.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.create().show();
        return;
    }

    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        JSONObject result = PluginUtil.location2Json(location);
        result.put("status", true);
        callbackContext.success(result);
        return;
    }

    PluginResult tmpResult = new PluginResult(PluginResult.Status.NO_RESULT);
    tmpResult.setKeepCallback(true);
    callbackContext.sendPluginResult(tmpResult);

    locationClient = new LocationClient(this.activity, new ConnectionCallbacks() {

        @Override
        public void onConnected(Bundle bundle) {
            LocationRequest request = new LocationRequest();
            int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
            if (enableHighAccuracy) {
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
            }
            request.setPriority(priority);
            locationClient.requestLocationUpdates(request, new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    JSONObject result;
                    try {
                        result = PluginUtil.location2Json(location);
                        result.put("status", true);
                        callbackContext.success(result);
                    } catch (JSONException e) {
                    }
                    locationClient.disconnect();
                }

            });
        }

        @Override
        public void onDisconnected() {
        }

    }, new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            int errorCode = connectionResult.getErrorCode();
            String errorMsg = GooglePlayServicesUtil.getErrorString(errorCode);
            PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
            callbackContext.sendPluginResult(result);
        }

    });
    locationClient.connect();
}