The documentation for Context.getSystemService states
Returns: The service or null if the name does not exist.
The list of accepted names is listed as
ACTIVITY_SERVICE
ALARM_SERVICE
AUDIO_SERVICE
BATTERY_SERVICE
CARRIER_CONFIG_SERVICE
CONNECTIVITY_SERVICE
DOWNLOAD_SERVICE
INPUT_METHOD_SERVICE
JOB_SCHEDULER_SERVICE
KEYGUARD_SERVICE
LAYOUT_INFLATER_SERVICE
LOCATION_SERVICE
MEDIA_ROUTER_SERVICE
NETWORK_STATS_SERVICE
NOTIFICATION_SERVICE
POWER_SERVICE
SEARCH_SERVICE
SENSOR_SERVICE
STORAGE_SERVICE
TELEPHONY_SERVICE
TELEPHONY_SUBSCRIPTION_SERVICE
UI_MODE_SERVICE
VIBRATOR_SERVICE
WIFI_SERVICE
WINDOW_SERVICE
Assuming I pass one of those names to getSystemService
at some point after the start of onCreate
in an Activity or Service, will the return value ever be null?
If so, are there any of the accepted names that will always return a non-null value, or do I need to null check the return values of all calls to getSystemService
?
Instant apps, for which PackageManager.isInstantApp()
returns true
, don't have access to the following system services:
DEVICE_POLICY_SERVICE,
FINGERPRINT_SERVICE,
SHORTCUT_SERVICE,
USB_SERVICE,
WALLPAPER_SERVICE,
WIFI_P2P_SERVICE},
WIFI_SERVICE,
WIFI_AWARE_SERVICE.
For these services this method will return null
.
Generally, if you are running as an instant app you should always check whether the result of this method is null.
And since the getSystemService()
method is annotated as @Nullable
, as a rule of thumb I would always check for null
:).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With