【发布时间】:2019-12-08 04:55:43
【问题描述】:
尽管我尽了最大的努力,我还是无法正确定位我的位置。这是我的 main.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
//new SecondFragment();
//TabLayout tabs = findViewById(R.id.tabs);
//tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
FontDrawable drawable = new FontDrawable(this, R.string.fa_plus_solid, true, false);
drawable.setTextColor(ContextCompat.getColor(this, android.R.color.white));
fab.setImageDrawable(drawable);
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();
}
});
//Check permission
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
latlang.Lat =location.getLatitude();
latlang.Lang =location.getLongitude();
}
}
});
}
}
}
latlang 在另一个文件中定义为:
public class latlang {
public static double Lat;
public static double Lang;
}
如果我在 latlang 中对值进行硬编码,一切都很好。但是,我当然想要last known location 的值。
请帮忙。
【问题讨论】:
-
首先——代码真的运行了吗?如果您创建了变量但从未设置它,则 0 是 int 的默认值。其次,getLastLocation 并不总是有效,因为由于电池原因,系统并不总是跟踪您的当前位置。因此,如果最近有其他东西要求位置,它只会有最后一个位置。您需要请求更新以确保位置。第三——记住这些将被异步调用的回调。不要假设数据会在任何特定时间范围内准备就绪。
-
@GabeSechan:是的,代码确实在模拟器和实际设备中运行。我在想我在这里设置值,但显然不是。 ` if (location != null) { latlang.Lat =location.getLatitude(); latlang.Lang =location.getLongitude(); }` 好心,如果你有时间,你能告诉我怎么做吗? SO充满了android位置问题,没有两个ans是相似的。
标签: android android-fusedlocation