用户启用GPS后获取位置更新

时间:2017-06-28 16:06:54

标签: android gps

我有一个简单的应用程序,目前只是要求必要的权限,如果GPS关闭,你会得到一个AlertDialog,询问你是否要打开它。接受后,被带到GPS选项,启用它,然后回到我的应用程序,我想更新位置,在这里我迷路了。

换句话说,我正在努力做到这里所说的:https://stackoverflow.com/a/43396965/7060082

不幸的是我无法完成它并且这个例子对我来说有点复杂。这是我的代码中显示的相关位:

    private void checkGPS() {
        manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.GPS_error)
                    .setCancelable(false)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(gps, 1);
                            getLatLon();
                        }
                    })
                    .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
            final AlertDialog alert = builder.create();
            alert.show();
        } else {
            getLatLon();
        }

    }

    private void getLatLon() {
        //manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = manager.getBestProvider(criteria, false);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            manager.getLastKnownLocation(provider);

            if (location != null) {
                Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();

            } else {
               // manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);


                //location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                /*
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
            */
            }
        }
    }

    @Override
    public void onLocationChanged(Location l) {
        location = l;
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();

    }

在要求获得ACCESS_FINE_LOCATION权限(也在清单上说明)之后,我致电 checkGPS()。如前所述,让我们启用或不启用GPS。如果启用,我会调用 getLatLon()。如果有lastKnownLocation,那么好,如果不是......

我迷路了。我调用 requestLocationUpdates ,然后无需等待 onLocationChanged 来接收位置更新并执行其余代码。我做得对吗?结果是我点击按钮,打开GPS。再次点击按钮,没有任何反应。

任何帮助都会有所帮助。 非常感谢你的时间。

3 个答案:

答案 0 :(得分:1)

我在这里开发了融合位置api演示应用程序和实用程序包。

General Utilities

如果对您有用,请尝试使用它。要使用融合位置api获取位置,您只需编写以下代码段...

new LocationHandler(this)
    .setLocationListener(new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        // Get the best known location
    }
}).start();

如果你想自定义它,只需在这里找到文档......

https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler

我根据您的需要编写了一个示例代码,这将在内部处理GPS启用/禁用对话框,试试这个......

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;

/**
 * Lets see how to use utilities module by implementing location listener.
 *
 * @author Khan
 */

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {

    private GoogleMap map;
    private Marker marker;
    private LocationHandler locationHandler;

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

        // Obtaining an instance of map
        FragmentManager manager = getSupportFragmentManager();
        SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        this.locationHandler = new LocationHandler(this)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(5000)
                .setFastestInterval(10000)
                .setLocationListener(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        this.map = map;
        this.locationHandler.start();
    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (marker == null) {
            marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
        } else {
            marker.setPosition(latLng);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationHandler != null) {
            locationHandler.stop();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationHandler.REQUEST_LOCATION) {
            locationHandler.start();
        }
    }
}

希望它会对你有所帮助。

答案 1 :(得分:0)

在禁用GPS的情况下,您的当前代码在等待getLatLon()之前不会等待用户做出选择。

当用户返回您的应用时,您需要添加onActivityResult()覆盖。

首先,对于禁用GPS的情况,请移除getLatLon()方法中对checkGPS()的来电:

private void checkGPS() {
    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.GPS_error)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(gps, 1);
                        //Remove this:
                        //getLatLon();
                    }
                })
                .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    } else {
        getLatLon();
    }
}

然后,添加onActivityResult()覆盖,再次检查设置,如果现在已启用,请致电getLatLon()

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        getLatLon();
    }
}

答案 2 :(得分:0)

经过一段时间忙于其他项目,回到这一个,我删除了getLatLon();来自checkGPS()的函数;功能就是这样,代码很好。我正在使用模拟器检查这是否有效,但我忘记了模拟器有一个固定的纬度和经度值,所以你得不到像真正的手机那样的更新,因此它看起来好像不能正常工作

newby错误的排序。无论如何,感谢您的优惠。看看做同样事情的不同方式很有意思。

Sartox