【问题标题】:What am I missing/what do I need to fix to make this code work?我缺少什么/我需要修复什么才能使此代码正常工作?
【发布时间】:2016-06-12 14:10:45
【问题描述】:

我对 Android 开发人员有点陌生,我想通过在单击按钮后检索最后一个已知位置并将其显示在 TextView 中来测试 Google 的位置服务。谁能告诉我应该如何修改此代码以使其正常工作?提前致谢:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{

GoogleApiClient googleApiClient;
String latitude, longitude;
Button gpsButton;
TextView displayGPS;
AlertDialog.Builder dB;
AlertDialog errorDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gpsButton.findViewById(R.id.gps_button);
    displayGPS.findViewById(R.id.display_gps);

    //create new google api client
     googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this)
             .addApi(LocationServices.API).build();
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

        if (lastLocation != null) {
            latitude = String.valueOf((lastLocation.getLatitude()));
            longitude = String.valueOf((lastLocation.getLongitude()));
            try {
                gpsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Resources res = getResources();
                        String gps = String.format(res.getString(R.string.lat_and_long), latitude, longitude);
                        displayGPS.setText(gps);
                    }
                });
            }catch (Exception e){
                displayGPS.setText(R.string.location_unavailable);
            }
        }
    }
}


@Override
public void onConnectionFailed(ConnectionResult cr){
    dB = new AlertDialog.Builder(this).setTitle("Connection Failed")
            .setMessage("Connection has failed.").setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    errorDialog = dB.create();
    errorDialog.show();
}
}

这里是 strings.xml 文件:

<resources>
    <string name="app_name">Location Test</string>
    <string name="find_gps">Find Your Last Location</string>
    <string name="ok">OK</string>
    <string name="lat_and_long">Latitude: %1s &amp; Longitude: %2$s</string>
    <string name="location_unavailable">Location unavailable.</string>
</resources>

【问题讨论】:

  • 首先我认为 %1s 应该在字符串资源中替换为 %1$s。否则,它会抛出任何错误消息吗?
  • 查看此答案以获取分步指导stackoverflow.com/a/38397092/5955362
  • 感谢@JaydeepPatel,该代码很有帮助,并帮助我修改了代码以使其正常工作
  • 感谢@AlexandreMartin 我错过了那个错字;现在我已经查看了其他人的一些示例代码,我已经能够修改我的代码以使其正常工作

标签: android


【解决方案1】:

首先你可以检查 lastLocation 是否为空:

if(lastLocation == null) {
    Log.d("TEST", "TEST"); //Prints out to LogCat
}

如果是这样,您必须通过以下方式请求当前位置

LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this);

(developer.android.com)
因为那时没有最后一个已知位置。

否则,如果应用程序刚刚崩溃,则不会从 UI 线程调用 displayGPS.setText(gps);。使用 runOnUiThread 并在此处设置文本。

编辑:
糟糕的是,setOnClickListener 中的所有内容都在 UI 线程上运行。对此感到抱歉。

【讨论】:

  • 好的,谢谢,我修改了我的代码,现在可以使用了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
相关资源
最近更新 更多