有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在继续Android之前正在等待GPS定位

我知道有很多类似的问题,但在我的搜索中找不到合适的答案

我的应用程序有一个依赖GPS定位的活动。如果应用程序在启动后立即运行,则由于位置为空的空指针异常等原因,应用程序将崩溃。我知道这些是我的编程错误,我应该处理异常,但在找到GPS定位之前,该活动仍然是无用的

当应用程序崩溃时,我会看到“搜索GPS”图标,如果这个图标保留足够长的时间,就会找到GPS位置,应用程序可以正常运行

我创建了另一个活动作为主屏幕,当找到GPS位置时,该按钮将链接到上述活动。问题是它似乎没有找到或正在寻找GPS信号。我的意思是,不会出现“搜索GPS”图标,并且该按钮永远不会启用。这个家庭活动的代码如下,我是否遗漏了什么

我的活动实现LocationListener,下面的代码位于活动“onCreate”方法中。“startExplore”启动我的GPS依赖活动

    exploreButton = (Button) findViewById(R.id.button1);

    exploreButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startExplore();
        }
    });

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider -> use
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } else {
        exploreButton.setEnabled(false);
        exploreButton.setText("Finding location . . .");
    }

这是我的“onLocationChanged”方法。正如我上面所说,与我的其他活动不同,我没有得到“搜索GPS”图标,尽管这与我的其他活动中使用的方法相同,但似乎找不到位置。那么,这是等待找到位置的正确方法吗?有人能识别出任何错误吗

public void onLocationChanged(Location location) {
    exploreButton.setEnabled(true);
    exploreButton.setText("Found signal");

}

共 (2) 个答案

  1. # 1 楼答案

    将其移出onCreate方法,或者将其放入处理程序中

    例如:

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
              //methods you want.
          }
        }, 100);
    
  2. # 2 楼答案

    打电话给 locationManager.requestLocationUpdates(locationProvider, 0, 0, this) 获取更新的位置。。这可能是问题的根源。。正因为如此,我认为只有“搜索GPS”没有启动