我有一个检查权限问题,总是在我的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)
最佳答案
您正在为getGeolocation()
提供上下文,但仍然在对象本身上调用getSystemService()
。
您可能要使用传递的上下文:
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
但是您也必须考虑Receiver and Process Lifecycle:
BroadcastReceiver对象仅在对
onReceive(Context, Intent)
的调用期间有效。一旦您的代码从该函数返回,系统将认为该对象已完成并且不再处于活动状态。 [...]这意味着对于长时间运行的操作,您通常将服务与BroadcastReceiver结合使用,以在整个操作过程中保持包含进程的活动状态。
因此,您最好重新实现应用程序的这一部分,并使用服务来更新位置。