Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which service returned by Context.getSystemService will never be null?

Tags:

android

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 getSystemServiceat 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?

like image 883
AA A Avatar asked May 26 '16 18:05

AA A


1 Answers

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 :).

like image 82
Ivo Stoyanov Avatar answered Sep 25 '22 11:09

Ivo Stoyanov