我正在写一个简单的应用程序。布局只有一个名为coords的textview,如下面的代码所示。应用程序使用位置侦听器来更新textview,将其值设置为当前位置的纬度和经度。
当我测试应用程序时,它会崩溃。首先,我试图注释掉负责设置textview值的行,因为我认为对字符串的修改可能会搞砸了......但仍然会崩溃。
然后我试图在
之间切换import com.google.android.gms.location.LocationListener;
和
import android.location.LocationListener;
但是当使用第一个时我得到了一个错误: 无法解析方法requestLocationUpdates(...)
任何提示,我做错了什么? 那是我现在的代码:
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
//import com.google.android.gms.location.LocationListener;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MapActivity extends AppCompatActivity {
TextView coords;
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
coords = (TextView)findViewById(R.id.tvCoords);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
//makeUseOfNewLocation(location);
//coords.setText(String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}