checkSelfPermission nullpointer 6.0

时间:2015-11-08 21:12:37

标签: android

我遇到检查permisions的问题总是说我在6.0中调试我的调试:

我做错了什么

public String getGeolocation(Context context){

    try{        
        int MY_PERMISSION_ACCESS_COURSE_LOCATION = 1000;         

        if ( ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSION_ACCESS_COURSE_LOCATION);
        }
        if ( Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //return 0 ;
        }
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Here is nullpointer
        //Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
            // Do something with the recent location fix
            //  otherwise wait for the update below
        }
        else {
            //mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,  0, 0, this);
        }
    }catch (Exception e){}
return geo;

}

//我使用此方法获取数据:

public void onLocationChanged(Location location) {
    if (location != null) {
        Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
        geo = ""+location.getLatitude() + " , " + location.getLongitude();
        mLocationManager.removeUpdates(this);
    }
}

Android studio的错误异常:

java.lang.IllegalStateException: System services not available to Activities before onCreate()

我在哪里调用getGeolocation()?

public class AlarmReceiverCustom extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
getGeolocation(context)

2 个答案:

答案 0 :(得分:1)

从错误中,您尝试在getGeolocation()被调用之前使用onCreate()。如果你这样做:

private String LOCATION = getGeoLocation(this);

这将是您的错误的来源。您需要将变量的初始化移到onCreate()内。

答案 1 :(得分:1)

您正在为getGeolocation()提供上下文,但您仍在对象本身上调用getSystemService()

您可能想要使用您传递的上下文:

mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

但你必须考虑Receiver and Process Lifecycle

  

BroadcastReceiver对象仅在调用onReceive(Context, Intent)期间有效。一旦您的代码从此函数返回,系统将认为该对象已完成且不再处于活动状态。 [...]

     

这意味着对于运行时间较长的操作,您通常会将一个服务与BroadcastReceiver结合使用,以便在整个操作过程中保持包含进程处于活动状态。

因此,您最好重新实现应用程序的这一部分,并使用服务来更新位置。