Location

本文介绍如何在Android应用中实现位置服务,包括在AndroidManifest.xml中添加必要的权限声明、使用LocationManager进行定位请求、处理不同来源的位置数据及更新监听等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加权限

//AndroidManifest.xml中
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

2.定位

//开始获取
    private void startLocation() {
        //请求超时处理
        mRunnable = new Runnable() {
            @Override
            public void run() {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mProgressDialog.dismiss();
                locationManager.removeUpdates(mListener);

                ((TextView) findViewById(R.id.show)).setText("Get Location time out");
                if (lastLocation != null)
                    Toast.makeText(MainActivity.this, "Use last location", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(MainActivity.this, "重启设备,重新获取", Toast.LENGTH_SHORT).show();
                mHandler.removeCallbacks(mRunnable);
            }
        };
        mHandler.postAtTime(mRunnable, 1 * 60 * 1000 * 10);

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

        //检查权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //获取最近的数据
        lastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//数据来源:网络提供
        if (lastLocation != null) {
            Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if ((gpsLocation != null) && isBetterLocation(gpsLocation, lastLocation)) {//比较,找到最好的
                lastLocation = gpsLocation;
            }
        } else {
            lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);//数据来源:GPS提供
        }

        if (lastLocation != null) {
            ((TextView) findViewById(R.id.show)).setText("Get Last Location->" + showLocation(lastLocation));
        }

        //开始定位
        if (mProgressDialog == null || !mProgressDialog.isShowing())
            mProgressDialog = ProgressDialog.show(this, "Notice", "Request Location...");
        if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {//网络
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListener);
            Toast.makeText(this, "Network location", Toast.LENGTH_SHORT).show();
        } else if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {//GPS
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
            Toast.makeText(this, "GPS location", Toast.LENGTH_SHORT).show();
        } else {//提示:无法定位
            mProgressDialog.dismiss();
            Toast.makeText(this, "Need Location!", Toast.LENGTH_SHORT).show();
        }
    }

    private LocationManager locationManager;
    private Location lastLocation;
    private ProgressDialog mProgressDialog;
    private Runnable mRunnable;
    private Handler mHandler = new Handler();

    private LocationListener mListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            mProgressDialog.dismiss();
            Toast.makeText(MainActivity.this, "Get Changed:" + showLocation(location), Toast.LENGTH_SHORT).show();
            ((TextView) findViewById(R.id.show)).setText("Location changed->" + showLocation(location));
        }

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

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };
@Override
    protected void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
        super.onDestroy();
    }

    private static final int TWO_MINUTES = 1000 * 60 * 2;

    //最佳经纬度
    protected boolean isBetterLocation(Location location,
                                       Location currentBestLocation) {
        if (currentBestLocation == null) {
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use
        // the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be
            // worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
                .getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and
        // accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /**
     * provider是否相同
     */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    //显示
    private String showLocation(Location location) {
        String providerStr = location.getProvider().equals(LocationManager.GPS_PROVIDER) ? "gps_provider" : "network_provider";
        return location != null ? ("latitude:" + location.getLatitude() + ", longitude:" + location.getLongitude() + ", provider:" + providerStr) : "";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值