【发布时间】: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 & Longitude: %2$s</string>
<string name="location_unavailable">Location unavailable.</string>
</resources>
【问题讨论】:
-
首先我认为 %1s 应该在字符串资源中替换为 %1$s。否则,它会抛出任何错误消息吗?
-
查看此答案以获取分步指导stackoverflow.com/a/38397092/5955362
-
感谢@JaydeepPatel,该代码很有帮助,并帮助我修改了代码以使其正常工作
-
感谢@AlexandreMartin 我错过了那个错字;现在我已经查看了其他人的一些示例代码,我已经能够修改我的代码以使其正常工作
标签: android