我对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>
答案 0 :(得分:0)
首先,您可以检查 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线程上运行。对不起。