當前位置: 首頁>>代碼示例>>Java>>正文


Java LocationManager.getLastKnownLocation方法代碼示例

本文整理匯總了Java中android.location.LocationManager.getLastKnownLocation方法的典型用法代碼示例。如果您正苦於以下問題:Java LocationManager.getLastKnownLocation方法的具體用法?Java LocationManager.getLastKnownLocation怎麽用?Java LocationManager.getLastKnownLocation使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在android.location.LocationManager的用法示例。


在下文中一共展示了LocationManager.getLastKnownLocation方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: register

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * 注冊
 * <p>使用完記得調用{@link #unregister()}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p>
 * <p>如果{@code minDistance}為0,則通過{@code minTime}來定時更新;</p>
 * <p>{@code minDistance}不為0,則以{@code minDistance}為準;</p>
 * <p>兩者都為0,則隨時刷新。</p>
 *
 * @param minTime     位置信息更新周期(單位:毫秒)
 * @param minDistance 位置變化最小距離:當位置距離變化超過此值時,將更新位置信息(單位:米)
 * @param listener    位置刷新的回調接口
 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失敗
 */
public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) {
    if (listener == null) return false;
    mLocationManager = (LocationManager) Utils.getContext().getSystemService(Context.LOCATION_SERVICE);
    mListener = listener;
    if (!isLocationEnabled()) {
        ToastUtils.showShortToastSafe("無法定位,請打開定位服務");
        return false;
    }
    String provider = mLocationManager.getBestProvider(getCriteria(), true);
    Location location = mLocationManager.getLastKnownLocation(provider);
    if (location != null) listener.getLastKnownLocation(location);
    if (myLocationListener == null) myLocationListener = new MyLocationListener();
    mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener);
    return true;
}
 
開發者ID:angcyo,項目名稱:RLibrary,代碼行數:31,代碼來源:LocationUtils.java

示例2: getLocation

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * PRECONDITION: The user has granted the system permission to access their device's location. May crash otherwise
 * @return the user's last known location if known, or null otherwise
 */
@SuppressWarnings("MissingPermission")
public static Location getLocation(Activity activity) {

    /**
     * Reference:
     * https://github.com/googlemaps/android-samples/blob/master/tutorials/CurrentPlaceDetailsOnMap
     */

    LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager == null)
        return null;

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0.0f, listener);
    final Location[] location = {null};
    location[0] = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    return location[0];
}
 
開發者ID:CMPUT301F17T15,項目名稱:CIA,代碼行數:22,代碼來源:LocationUtilities.java

示例3: getLastKnownLocation

import android.location.LocationManager; //導入方法依賴的package包/類
private Location getLastKnownLocation(){
    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 locationManager =
            (LocationManager) this.getSystemService( LOCATION_SERVICE );
    List<String> providers = locationManager.getProviders( true );
    Location bestLocation = null;
    for( String provider : providers ){
        Location l = locationManager.getLastKnownLocation( provider );
        if( l == null ){
            continue;
        }
        if( bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy() ){
            bestLocation = l; // Found best last known location;
        }
    }
    return bestLocation;
}
 
開發者ID:TheKhaeng,項目名稱:nongbeer-mvp-android-demo,代碼行數:20,代碼來源:MapActivity.java

示例4: register

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * 注冊
 * <p>使用完記得調用{@link #unregister()}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p>
 * <p>如果{@code minDistance}為0,則通過{@code minTime}來定時更新;</p>
 * <p>{@code minDistance}不為0,則以{@code minDistance}為準;</p>
 * <p>兩者都為0,則隨時刷新。</p>
 *
 * @param minTime     位置信息更新周期(單位:毫秒)
 * @param minDistance 位置變化最小距離:當位置距離變化超過此值時,將更新位置信息(單位:米)
 * @param listener    位置刷新的回調接口
 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失敗
 */
public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) {
    if (listener == null) return false;
    mLocationManager = (LocationManager) Utils.getContext().getSystemService(LOCATION_SERVICE);
    mListener = listener;
    if (!isLocationEnabled()) {
        Log.d(TAG, "無法定位,請打開定位服務");
        return false;
    }
    String provider = mLocationManager.getBestProvider(getCriteria(), true);
    Location location = mLocationManager.getLastKnownLocation(provider);
    if (location != null) listener.getLastKnownLocation(location);
    if (myLocationListener == null) myLocationListener = new MyLocationListener();
    mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener);
    return true;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:31,代碼來源:LocationUtils.java

示例5: getLastKnownLocation

import android.location.LocationManager; //導入方法依賴的package包/類
private void getLastKnownLocation() {
    Context context = this.getContext();

    Location gpsLocation = null;
    Location networkLocation = null;

    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (PermissionUtils.checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION))
        gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (PermissionUtils.checkPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION))
        networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    Location location = betterLocation(gpsLocation, networkLocation);
    if (location != null) this.output(new Geolocation(location));
    this.finish();
}
 
開發者ID:PrivacyStreams,項目名稱:PrivacyStreams,代碼行數:17,代碼來源:LastKnownLocationProvider.java

示例6: getBestLastKnownLocation

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * Restituice la posizione più accurata e più recente del dispositivo, scelta tra tutti i location provider disponibili.
 */
public static Location getBestLastKnownLocation(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    Location bestLocation = null;

    for (String provider : providers) {
        try {
            Location location = locationManager.getLastKnownLocation(provider);
            if (bestLocation == null || location != null
                    && location.getElapsedRealtimeNanos() > bestLocation.getElapsedRealtimeNanos()
                    && location.getAccuracy() > bestLocation.getAccuracy())
                bestLocation = location;
        } catch (SecurityException ignored) {
        }
    }

    return bestLocation;
}
 
開發者ID:gvinciguerra,項目名稱:custode,代碼行數:22,代碼來源:LocationService.java

示例7: register

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * 注冊
 * <p>使用完記得調用{@link #unregister()}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p>
 * <p>需添加權限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p>
 * <p>如果{@code minDistance}為0,則通過{@code minTime}來定時更新;</p>
 * <p>{@code minDistance}不為0,則以{@code minDistance}為準;</p>
 * <p>兩者都為0,則隨時刷新。</p>
 *
 * @param minTime     位置信息更新周期(單位:毫秒)
 * @param minDistance 位置變化最小距離:當位置距離變化超過此值時,將更新位置信息(單位:米)
 * @param listener    位置刷新的回調接口
 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失敗
 */
public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) {
    if (listener == null) return false;
    mLocationManager = (LocationManager) Utils.getContext().getSystemService(Context.LOCATION_SERVICE);
    mListener = listener;
    if (!isLocationEnabled()) {
        ToastUtils.showShortSafe("無法定位,請打開定位服務");
        return false;
    }
    String provider = mLocationManager.getBestProvider(getCriteria(), true);
    Location location = mLocationManager.getLastKnownLocation(provider);
    if (location != null) listener.getLastKnownLocation(location);
    if (myLocationListener == null) myLocationListener = new MyLocationListener();
    mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener);
    return true;
}
 
開發者ID:pan2yong22,項目名稱:AndroidUtilCode-master,代碼行數:31,代碼來源:LocationUtils.java

示例8: getCurrentPosition

import android.location.LocationManager; //導入方法依賴的package包/類
/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and
 *        highAccuracy (boolean)
 */
@ReactMethod
public void getCurrentPosition(
    ReadableMap options,
    final Callback success,
    Callback error) {
  LocationOptions locationOptions = LocationOptions.fromReactMap(options);

  try {
    LocationManager locationManager =
        (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
    if (provider == null) {
      error.invoke(PositionError.buildError(
              PositionError.PERMISSION_DENIED,
              "No location provider available."));
      return;
    }
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null &&
        SystemClock.currentTimeMillis() - location.getTime() < locationOptions.maximumAge) {
      success.invoke(locationToMap(location));
      return;
    }
    new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error)
        .invoke();
  } catch (SecurityException e) {
    throwLocationPermissionMissing(e);
  }
}
 
開發者ID:qq565999484,項目名稱:RNLearn_Project1,代碼行數:37,代碼來源:LocationModule.java

示例9: addLocationListener

import android.location.LocationManager; //導入方法依賴的package包/類
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void addLocationListener() {
    // Note: Use the Fused Location Provider from Google Play Services instead.
    // https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

    mLocationManager =
            (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
    Log.d("BoundLocationMgr", "Listener added");

    // Force an update with the last location, if available.
    Location lastLocation = mLocationManager.getLastKnownLocation(
            LocationManager.GPS_PROVIDER);
    if (lastLocation != null) {
        mListener.onLocationChanged(lastLocation);
    }
}
 
開發者ID:googlecodelabs,項目名稱:android-lifecycles,代碼行數:18,代碼來源:BoundLocationManager.java

示例10: getLocation

import android.location.LocationManager; //導入方法依賴的package包/類
public Location getLocation() {

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "Permission not granted", Toast.LENGTH_SHORT).show();
            return null;
        }
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
            Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            return l;
        } else {
            Toast.makeText(context, "Please enable GPS !", Toast.LENGTH_LONG).show();
        }
        return null;
    }
 
開發者ID:StickyBoi,項目名稱:SkateSpot,代碼行數:18,代碼來源:GPSTracker.java

示例11: getLocation

import android.location.LocationManager; //導入方法依賴的package包/類
public Location getLocation() {
    try {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (ActivityCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            }

            if (isNetworkEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}
 
開發者ID:a-deda,項目名稱:share-location,代碼行數:34,代碼來源:GPSHelper.java

示例12: getLastLocation

import android.location.LocationManager; //導入方法依賴的package包/類
private Location getLastLocation() {
    LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.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;
}
 
開發者ID:pooyafaroka,項目名稱:PlusGram,代碼行數:13,代碼來源:LocationActivity.java

示例13: getLocation

import android.location.LocationManager; //導入方法依賴的package包/類
public void getLocation(Fragment fragment) {
    this.fragment = fragment;
    boolean locationPermissionFlag = util.checkPermission(locationPermissions,
            activity);
    if (locationPermissionFlag) {
        fragment.requestPermissions(locationPermissions, Configure.LOCATION_PERMISSION_CODE);
    }else{
        locationManager = (LocationManager) activity.getSystemService(Context.
                LOCATION_SERVICE);
        String provider;
        List<String> providerList = locationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(activity, "請連接網絡或打開GPS",
                    Toast.LENGTH_LONG).show();
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider, 2000, 10, this);
        if (location != null) {
            getLocation(location);
        }
    }
}
 
開發者ID:victorySSS,項目名稱:readingNotes,代碼行數:28,代碼來源:LocationUtil.java

示例14: getProvider

import android.location.LocationManager; //導入方法依賴的package包/類
public static String getProvider(Context ctx, LocationManager mLocationManager) {
    String mProviderName = "";
    if (isNetworkConnected(ctx)) {
        boolean hasGpsProvide;
        boolean hasNetWorkProvider;
        if (mLocationManager.getProvider("gps") != null) {
            hasGpsProvide = true;
        } else {
            hasGpsProvide = false;
        }
        if (mLocationManager.getProvider("network") != null) {
            hasNetWorkProvider = true;
        } else {
            hasNetWorkProvider = false;
        }
        Helper.showLog(TAG, " hasGpsProvide =" + hasGpsProvide + " hasNetWorkProvider =" +
                hasNetWorkProvider);
        boolean isGpsEnabled = isGPSProviderAvaliable(ctx);
        boolean isWIFIEnabled = isWIFIProviderAvaliable(ctx);
        if (!hasGpsProvide && !hasNetWorkProvider) {
            Helper.showToast(ctx, (int) R.string.xw);
            return ctx.getString(R.string.xw);
        } else if (!hasGpsProvide && hasNetWorkProvider) {
            Helper.showLog(TAG, ">>>>>>>>>>>>>>>only network provider");
            if (isWIFIEnabled) {
                mProviderName = "network";
            } else {
                Helper.showLog(TAG, ">>>>>>>>>>>>>>>no network avaliable");
                return null;
            }
        } else if (!hasGpsProvide || hasNetWorkProvider) {
            Helper.showLog(TAG, ">>>>>>>>>>>>>>>hasallprovider");
            if (!isGpsEnabled && !isWIFIEnabled) {
                Helper.showLog(TAG, ">>>>>>>>>>>>>>>no GPS or NETWORK avaliable");
                return null;
            } else if (isGpsEnabled && !isWIFIEnabled) {
                mProviderName = "gps";
            } else if (!isGpsEnabled && isWIFIEnabled) {
                Helper.showLog(TAG, ">>>>>>>>>>>>>>>network avaliable");
                mProviderName = "network";
            } else if (isGpsEnabled && isWIFIEnabled) {
                Helper.showLog(TAG, ">>>>>>>>>>>>>>>all avaliable");
                mProviderName = "gps";
                if (mLocationManager.getLastKnownLocation("gps") == null) {
                    Helper.showLog(TAG, ">>>>>>>>>>>>>>>all avaliable but location is null");
                    mProviderName = "network";
                }
            }
        } else {
            Helper.showLog(TAG, ">>>>>>>>>>>>>>>only GPS provider");
            if (isGpsEnabled) {
                mProviderName = "gps";
            } else {
                Helper.showLog(TAG, ">>>>>>>>>>>>>>>no GPS avaliable");
                return null;
            }
        }
    }
    Helper.showToast(ctx, ctx.getString(R.string.gu));
    return mProviderName;
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:62,代碼來源:LocationUtils.java

示例15: getLocation

import android.location.LocationManager; //導入方法依賴的package包/類
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);
        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {
            showSettingsAlert();
        }
        else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
                    }
                }
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                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);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    mLastestLocation = new LatLng(latitude, longitude);
    return location;
}
 
開發者ID:sega4revenge,項目名稱:Sega,代碼行數:68,代碼來源:GPSTracker.java


注:本文中的android.location.LocationManager.getLastKnownLocation方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。