如何使用GPS获取用户的位置

时间:2017-06-13 20:50:01

标签: java android gps location

我有一个活动,其中我有一个文本视图,我想显示用户当前位置和特定地址之间的距离。我有地址的纬度和逻辑,但我的问题是获取用户的位置。我的目标是在创建活动的时候,当我想要在没有按任何按钮的情况下获得他的位置时。我尝试了多种方法:getLastKnownLocation,onLocation更改等,但返回的值始终为null。

重要的是要注意我在模拟器上运行应用程序。

示例代码:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_list);

        Bundle bundleUser = getIntent().getExtras();
        final String owneruser = bundleUser.getString("username");

        Bundle bundleType = getIntent().getExtras();
        String type = bundleType.getString("type");

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        final TextView t = (TextView) findViewById(R.id.textView2);
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                longitude = location.getLongitude();
                latitude = location.getLatitude();
                t.append("\n " + location.getLongitude() + " " + location.getLatitude());
            }

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

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);
            }
        };
        final Location userLocation = new Location("");
        userLocation.setLatitude(latitude);
        userLocation.setLongitude(longitude);
}

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 10:
                update();
                break;
            default:
                break;
        }
    }

    void update(){
        // first check for permissions
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                        ,10);
            }
        }
        else {
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    }

1 个答案:

答案 0 :(得分:0)

将您的活动实施到LocationListener:

public class MyActivity extends AppCompatActivity implements LocationListener {
 private Location userLocation = new Location("");


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

      @Override
public void onLocationChanged(Location location) {
    if(location != null){
        userLocation.setLatitude(location.getLatitude());
        userLocation.setLongitude(location.getLongitude());
    }
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

尝试此操作以授予权限:

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
        }
    }

并在清单中添加:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />