我目前正在做一个项目,其中应用程序将获取用户的当前位置并将其显示在文本视图中,所有内容都发生在片段内。我没有得到任何错误但由于某种原因它不起作用..
以下是我的代码的一部分。 清单和导入中的所有权限都很好..
另一个奇怪的事情是当我点击按钮时,我的应用程序在我的logcat中没有显示任何内容。
注意:所有代码都在片段
中希望有人可以给我一个提示或两个谢谢!
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
private LocationManager locationManager;
private LocationListener listener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myinflate = inflater.inflate(R.layout.fragment_home, container, false);
final TextView cords = (TextView) myinflate.findViewById(R.id.welcome);
final Button butt = (Button) myinflate.findViewById(R.id.button1);
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
cords.setText(location.getLatitude() +" "+location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
butt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
});
return myinflate;
}
答案 0 :(得分:0)
这在Android M版本或更高版本
上发生这个区块:
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
如果应用程序没有权限,则指示Button事件处理程序不执行任何操作。
解决方案是从片段中请求权限:
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(LocationSurface.PERMISSIONS_LOCATION, AppConstants.REQUEST_CODE_PERMISSIONS);
}
}else{....}
或者,从模拟器,设置 - >应用程序 - >你的应用 - >权限 - >授予位置权限