【问题标题】:last known location is always 0 [duplicate]最后一个已知位置始终为 0 [重复]
【发布时间】:2019-12-08 04:55:43
【问题描述】:

尽管我尽了最大的努力,我还是无法正确定位我的位置。这是我的 ma​​in.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


【解决方案1】:

问题是您尝试在授予权限之前获取位置。 调用requestPermissions() 后,您会立即尝试在显示权限对话框时获取位置,这意味着在您看到权限对话框时正在执行获取位置的代码。这就是为什么在活动中有onRequestPermissionsResult 函数仅在用户完成权限对话框后才报告的原因。 您需要在onRequestPermissionsResult() 中获取位置。

您的代码中的第二个问题是您只有在未授予权限时才能获取位置。您的代码不会处理已授予权限的情况。

以下是解决此问题的方法:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     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);
     } else {
      fetchLocation();
     }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
     String[] permissions, int[] grantResults) {
     switch (requestCode) {
      case 101:
       {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 &&
         (grantResults[0] == PackageManager.PERMISSION_GRANTED ||
          grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
         // permission was granted
         fetchLocation()
        } else {
         Show some error
        }
        return;
       }

       // other 'case' lines to check for other
       // permissions this app might request.
     }
    }

    public void fetchLocation() {
     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();
        }
       }
      });

    }

基本上,创建一个单独的函数来获取位置。您将从 2 个位置调用此函数。第一个在授予权限时在onCreate,第二个在onPermissionResult。不要忘记处理权限错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多