【问题标题】:Location isalways null位置始终为空
【发布时间】:2020-04-01 14:48:26
【问题描述】:

我正在构建一个速度计应用程序,为此我正在使用 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();
    }
}

如果你在上面的 sn-ps 中没有发现问题,这里是完整的 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) {

}
}

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

【问题讨论】:

    标签: java android android-studio geolocation location


    【解决方案1】:

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

    【讨论】:

    • 好的,我确实将 lm == null 更改为 lm != null 现在它变得更奇怪了 - 在 android studio 模拟器上它并没有真正要求权限,然后显示 0.00 作为速度。当我在手机中安装 apk 时(检查了多个设备,相同的行为),它会请求许可,我允许它,然后我必须手动打开我的设备位置,然后应用程序崩溃。当我再次打开时,它不会崩溃,但总是会再次显示“-.- km/hr”作为速度。应用是否因某种原因无法获取位置?
    • 另外,我受够了并制作了另一个应用程序,它有点类似的问题,但它更具体。检查那里:stackoverflow.com/questions/60988766/…
    • 但是你为什么要在你的 doStuff 函数中请求权限,这个函数只有在权限被授予的情况下才会被调用?
    • 我看到了那个错误并重新制作了应用程序,在新链接中,请检查
    • 您确定更改了问题中的代码吗?
    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多