Android 获取非空的systemService

Android 获取非空的systemService,android,null,system-services,Android,Null,System Services,每次我将getSystemService分配给某个变量时,我都必须稍后检查它是否为null,例如 LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (mLocationManager != null) {...} 有没有办法确保它不为null?一种方法是编写getSystemService(),这样它就不会返回null对象(即,如果无法创建nul

每次我将getSystemService分配给某个变量时,我都必须稍后检查它是否为null,例如

LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager != null) {...}

有没有办法确保它不为null?

一种方法是编写
getSystemService()
,这样它就不会返回null对象(即,如果无法创建null对象,则抛出)。当然,您必须将调用包装在
catch
块中。如果你没有
getSystemService
代码,那么你就无能为力了。所以总体来说,我想你已经尽了最大努力了。我想我从未见过location manager返回空值。你添加权限了吗?Ofc我添加了,它对我来说从来都不是空的,但这只是一种可能性,android studio正在警告我,所以我徘徊。。。另一方面,这个
NotificationManager mNotificationManager=getSystemService(NotificationManager.class)在上百次/上千次发射后,有一次撞到我身上吗