检查片段中LocationServices.FusedLocationApi的权限时,getContext()出错

时间:2017-04-26 05:10:35

标签: android

java.lang.NullPointerException:尝试调用虚方法' int android.content.Context.checkPermission(java.lang.String,int,int)'在空对象引用上

   if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    .....
            return;
        }

1 个答案:

答案 0 :(得分:0)

您的上下文

Context context = getActivity();//if using fragment
Context context = ActivityName.this;//if using Activity

您可以使用以下方法

 if(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}