位置始终为null

时间:2020-04-01 14:48:26

标签: java android android-studio geolocation location

我正在构建一个速度表应用程序,并使用location getSpeed()命令来实现。 我或多或少地遵循了本教程: https://www.youtube.com/watch?v=ua4jY0lBvCA&list=FLEK0r5UuT755jVeeb70m_tg&index=2&t=0s

该应用程序安装在我的手机中,然后打开,询问权限等。但不会更新速度。 我猜问题出在这里,因为我在需要速度的文本视图中看到“ -.- km / hr”:

    @Override
public void onLocationChanged(Location location) {
    //Set up the text view with the location and getSpeed()
    TextView txt = (TextView) this.findViewById(R.id.textView);

    if (location == null) {
        txt.setText("-.- km/hr");
    } else {
        float nCurrentSpeed = location.getSpeed() * 3.6f;
        txt.setText(String.format("%.2f", nCurrentSpeed) + " km/hr");
    }
}

此外,它还说“正在等待我在这里提到的GPS信号:

    //Custom function for setting up location manager
private void doStuff() {
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    if (lm == null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    } else {
        Toast.makeText(this,"Waiting for GPS signal",Toast.LENGTH_SHORT).show();
    }
}

如果您没有在上面的代码段中看到问题,请查看完整的MainActivity.java

//implement LocationListener and apply its methods
public class MainActivity extends AppCompatActivity implements LocationListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    //checks permission, goes to onRequestPermissionsResult
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // If permission is not granted,
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
    } else {

        //starts the program if permission is granted
        doStuff();
    }
    this.onLocationChanged(null);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

//Code for checking permissions
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 1000) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            doStuff();
        }
        finish();
    }

}

@Override
public void onLocationChanged(Location location) {
    //Set up the text view with the location and getSpeed()
    TextView txt = (TextView) this.findViewById(R.id.textView);

    if (location == null) {
        txt.setText("-.- km/hr");
    } else {
        float nCurrentSpeed = location.getSpeed() * 3.6f;
        txt.setText(String.format("%.2f", nCurrentSpeed) + " km/hr");
    }
}

//Custom function for setting up location manager
private void doStuff() {
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    if (lm == null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    } else {
        Toast.makeText(this,"Waiting for GPS signal",Toast.LENGTH_SHORT).show();
    }
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

我是一个非常新的程序员,您可以说这是我制作的第一个应用程序,因此很有可能这是一个新手错误。请帮忙。

1 个答案:

答案 0 :(得分:0)

请求位置更新的唯一时间是在doStuff函数中,即lm==null ...您应在lm!=null时请求它们。