我尝试了另一种方法,因为我并不真正理解“requestsingleupdate”是如何工作的
所以我看了一些使用“requestlocationupdates”的教程,但问题是它也不起作用。
这是我的新密码:
// All import stuffs
public class AjouterBancFragment extends Fragment {
TextView textViewLongLat;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.ajouter_banc, container, false);
textViewLongLat = v.findViewById(R.id.textViewLongLat);
Button buttonAdd = v.findViewById(R.id.buttonAjouterBanc);
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new AjouterBancFragment.MyLocationListener();
if ((ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
Toast.makeText(getContext(), "OK", Toast.LENGTH_SHORT).show(); // Toast is showing
}
}
});
return v;
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
Toast.makeText(getContext(), "OnLocationChanged", Toast.LENGTH_SHORT).show(); // Toast not showing
String longitude = "Longitude: " + loc.getLongitude();
String latitude = "Latitude: " + loc.getLatitude();
String s = longitude + "\n" + latitude;
textViewLongLat.setText(s);
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(getContext(), "onProviderDisabled", Toast.LENGTH_SHORT).show(); // Toast not showing
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getContext(), "on ProviderEnabled", Toast.LENGTH_SHORT).show(); // Toast not showing
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getContext(), "onStatusChanged", Toast.LENGTH_SHORT).show(); // Toast not showing
}
}
}
我放置toast消息是为了查看代码的步骤,但是我只有一个toast消息出现(它在代码中被注释)。如果有人知道为什么不起作用,我很感兴趣!
谢谢你。