requestLocationUpdates以获取GPS无效

问题描述 投票:0回答:1

我是Android的新手,请尝试举一个示例来获取GPS位置。我在网上冲浪,有以下代码。单击按钮获取GPS后,该程序将崩溃。我发现当我调用locationManager.requestLocationUpdates(commandStr,1000,0,locationListener)时似乎有问题。我将其跟踪到requestLocationUpdates中,发现它在Looper类中崩溃了

public final class Looper {
    Looper(boolean quitAllowed) {
        throw new RuntimeException("Stub!");
    }

    public static void prepare() {
        throw new RuntimeException("Stub!");
    }

    public static void prepareMainLooper() {
        throw new RuntimeException("Stub!");
    }

    public static Looper getMainLooper() {
        throw new RuntimeException("Stub!");
    }

    public static void loop() {
        throw new RuntimeException("Stub!");
    }

下面是完整的代码,任何人都知道程序的哪一部分是错误的

public class MainActivity extends AppCompatActivity {

    private TextView tvLocation;
    private Button btGetLocation;
    private LocationManager locationManager;
    private String commandStr;

    private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;

    public LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            tvLocation.setText("經度" + location.getLongitude() + "\n緯度" + location.getLatitude());
        }

        @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 onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        commandStr = LocationManager.GPS_PROVIDER;
        // LocationManager.GPS_PROVIDER //使用GPS定位
        // LocationManager.NETWORK_PROVIDER //使用網路定位

        tvLocation = (TextView) findViewById(R.id.textView);
        btGetLocation = (Button) findViewById(R.id.button);

        btGetLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                // LocationManager可以用來獲取當前的位置,追蹤設備的移動路線
                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) {
                    // 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.
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                            MY_PERMISSION_ACCESS_COARSE_LOCATION);
                    return;
                }

                locationManager.requestLocationUpdates(commandStr, 1000, 0, locationListener);
                // 事件的條件設定為時間間隔1秒,距離改變0米,設定監聽位置變化

                Location location = locationManager.getLastKnownLocation(commandStr);
                if (location != null)
                    tvLocation.setText("經度"+location.getLongitude()+"\n緯度"+location.getLatitude());
                else
                    tvLocation.setText("定位中");
                // location.getLongitude() //取得經度
                // location.getLatitude() //取得緯度
                // location.getAltitude() //取得海拔高度
            }
        });



    }


}
android android-gps
1个回答
0
投票

这里有一些代码示例:

public class Activity extends AppCompatActivity{

//variables for GPS data
private LocationManager locationManager;
private Location location;
private int minTime = 1000 //=1s
private int minDistance = 5 //=5m
private List<String> providers; 
private final ActivityLocationListener locationListener = new ActivityLocationListener();

@Override
protected void onCreate(){

super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_file);

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        providers = locationManager.getProviders(true);
        //this will print you the available providers in your LogCat
        //in some virtual devices network is not available
        Log.d(NoteMapActivity.this.getClass().getSimpleName(), "available providers:\n" + providers);

}

public void onButtClick(View view){

this.requestLocationUpdates();
}

public void requestLocationUpdates(){

locationManager = (LocationManager) getSystemService(LOCATON_SERVICE);

//with this following code you will call onLocationChanged()
if (providers.contains("gps")){
            //"permisson check"
            try {
                locationManager.requestLocationUpdates("gps", minTime, minDistance, locationListener);
            } catch (SecurityException ex){
                Log.e(getClass().getSimpleName(), "no permisson: " + ex.toString());
            }
//if gps is not available you can use "network" or "passive" instead, maybe with if-else conditions

}

//create a class inside of this one!
class ActivityLocationListener implements LocationListener{
@Override
        public void onLocationChanged(Location location) {
            currentLocation = location;
            Log.d(NoteMapActivity.this.getClass().getSimpleName(), "received location:\n" + currentLocation.getLatitude() + ", " + currentLocation.getLongitude());
            addCurrentLocationMarkerToMap();
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
}

}
© www.soinside.com 2019 - 2024. All rights reserved.