Package com.castlabs.android.player
Class PlayerService
java.lang.Object
android.content.Context
android.content.ContextWrapper
android.app.Service
com.castlabs.android.player.PlayerService
- All Implemented Interfaces:
ComponentCallbacks
,ComponentCallbacks2
This class implements a bounded Android Service that can be used to start a
PlayerController
in a service, send the player to background to continue audio playback, and resume video playback
from a background session. The service returns PlayerService.Binder
as its binder implementation.
A typical usage of this service is the following setup. You overwrite your activities
onCreate()
and on onResume()
callbacks. In onCreate()
, you acquire a
reference to the PlayerView
and store the passed intent to start playback later. Note
that we are not interacting with the PlayerController
in the onCreate()
since
the controller will be initialized by the service when a connection is established.
@
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
playerView = findViewById(R.id.player_View);
playbackIntent = getIntent();
}
@Override
protected void onStart() {
super.onStart();
playerView.getLifecycleDelegate().start(this);
}
@
Override
protected void onResume() {
super.onResume();
Intent serviceIntent = new Intent(this, PlayerService.class);
bindService(serviceIntent, playerServiceConnection, Context.BIND_AUTO_CREATE);
}
The service connection can then be implemented as follows:
private final ServiceConnection playerServiceConnection = new ServiceConnection() {
@
Override
public void onServiceConnected(ComponentName name, IBinder service) {
// get the service binder and initialize the service
playerServiceBinder = (PlayerService.Binder) service;
boolean backgrounded = playerServiceBinder.init(playerView);
// from now on you can use playerView.getPlayerController() to interact with the controller
if (!backgrounded) {
if (playbackIntent != null) {
// The player was not restored from background and we have a bundle to open.
// This indicates that we came from an onCreate() call instead of resuming
// an existing activity
playerView.getPlayerController().open(playbackIntent);
} else {
// the player was not restored from background and no bundle was passed.
// In this case we delegate to the views lifecycle delegate to eventually restore
// a session
playerView.getLifecycleDelegate().resume();
}
}
playbackIntent = null;
}
@
Override
public void onServiceDisconnected(ComponentName name) {
playerServiceBinder.release(playerView, true);
playerServiceBinder = null;
}
};
This service connection handles the three cases where
- The controller is restored from a background session
- No background session was found but an existing Intent exists that can be used to open playback
- No background session was found and the Activity was resumed (here indicated by an empty
playbackIntent
). In this case we are delegating to the views lifecycle delegate
onStop()
method to send
a current session to background using the service binder.
@
Override
protected void onStop() {
super.onStop();
if (playerServiceBinder != null) {
if (!isFinishing()) {
// The activity is not finishing but left through other means, i.e. Home button.
// In this case, we send the player to background and display a notification
playerServiceBinder.releaseToBackground(
playerView,
NOTIFICATION_ID,
createBackgroundNotification(),
true);
} else {
// We are not sending the player to background since the activity is finishing
// so we fully release the player
playerServiceBinder.release(playerView, true);
}
// in both cases we we unbind the service
unbindService(playerServiceConnection);
playerServiceBinder = null;
} else {
// We have no service connection, so we release the player without background playback
playerView.getLifecycleDelegate().releasePlayer(false);
}
}
Note the usage of Activity.isFinishing()
here. We only send the player to background
if the activity is not finishing. This indicates that for example the Home button was pressed.
The activity will be finishing if the user clicks the back button. In that case, we do not want
to continue background playback but release the player fully.- Since:
- 3.0.0
-
Nested Class Summary
Modifier and TypeClassDescriptionclass
This is the binder that will be returned by when a service connection is bound to the player service.static interface
Implementation of the interface can receive notification intents from thePlayerService
.Nested classes/interfaces inherited from class android.content.Context
Context.BindServiceFlags
-
Field Summary
Fields inherited from class android.app.Service
START_CONTINUATION_MASK, START_FLAG_REDELIVERY, START_FLAG_RETRY, START_NOT_STICKY, START_REDELIVER_INTENT, START_STICKY, START_STICKY_COMPATIBILITY, STOP_FOREGROUND_DETACH, STOP_FOREGROUND_LEGACY, STOP_FOREGROUND_REMOVE
Fields inherited from class android.content.Context
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APP_OPS_SERVICE, APP_SEARCH_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BATTERY_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_ACTIVITY_STARTS, BIND_ALLOW_OOM_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_EXTERNAL_SERVICE, BIND_EXTERNAL_SERVICE_LONG, BIND_IMPORTANT, BIND_INCLUDE_CAPABILITIES, BIND_NOT_FOREGROUND, BIND_NOT_PERCEPTIBLE, BIND_SHARED_ISOLATED_PROCESS, BIND_WAIVE_PRIORITY, BIOMETRIC_SERVICE, BLOB_STORE_SERVICE, BLUETOOTH_SERVICE, BUGREPORT_SERVICE, CAMERA_SERVICE, CAPTIONING_SERVICE, CARRIER_CONFIG_SERVICE, CLIPBOARD_SERVICE, COMPANION_DEVICE_SERVICE, CONNECTIVITY_DIAGNOSTICS_SERVICE, CONNECTIVITY_SERVICE, CONSUMER_IR_SERVICE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESTRICTED, CREDENTIAL_SERVICE, CROSS_PROFILE_APPS_SERVICE, DEVICE_ID_DEFAULT, DEVICE_ID_INVALID, DEVICE_LOCK_SERVICE, DEVICE_POLICY_SERVICE, DISPLAY_HASH_SERVICE, DISPLAY_SERVICE, DOMAIN_VERIFICATION_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, EUICC_SERVICE, FILE_INTEGRITY_SERVICE, FINGERPRINT_SERVICE, GAME_SERVICE, GRAMMATICAL_INFLECTION_SERVICE, HARDWARE_PROPERTIES_SERVICE, HEALTHCONNECT_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, IPSEC_SERVICE, JOB_SCHEDULER_SERVICE, KEYGUARD_SERVICE, LAUNCHER_APPS_SERVICE, LAYOUT_INFLATER_SERVICE, LOCALE_SERVICE, LOCATION_SERVICE, MEDIA_COMMUNICATION_SERVICE, MEDIA_METRICS_SERVICE, MEDIA_PROJECTION_SERVICE, MEDIA_ROUTER_SERVICE, MEDIA_SESSION_SERVICE, MIDI_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_NO_LOCALIZED_COLLATORS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NETWORK_STATS_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, OVERLAY_SERVICE, PEOPLE_SERVICE, PERFORMANCE_HINT_SERVICE, POWER_SERVICE, PRINT_SERVICE, RECEIVER_EXPORTED, RECEIVER_NOT_EXPORTED, RECEIVER_VISIBLE_TO_INSTANT_APPS, RESTRICTIONS_SERVICE, ROLE_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, SHORTCUT_SERVICE, STATUS_BAR_SERVICE, STORAGE_SERVICE, STORAGE_STATS_SERVICE, SYSTEM_HEALTH_SERVICE, TELECOM_SERVICE, TELEPHONY_IMS_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, TEXT_CLASSIFICATION_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TV_INPUT_SERVICE, TV_INTERACTIVE_APP_SERVICE, UI_MODE_SERVICE, USAGE_STATS_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_MANAGER_SERVICE, VIBRATOR_SERVICE, VIRTUAL_DEVICE_SERVICE, VPN_MANAGEMENT_SERVICE, WALLPAPER_SERVICE, WIFI_AWARE_SERVICE, WIFI_P2P_SERVICE, WIFI_RTT_RANGING_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
Fields inherited from interface android.content.ComponentCallbacks2
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
-
Constructor Summary
-
Method Summary
Methods inherited from class android.app.Service
getApplication, getForegroundServiceType, onConfigurationChanged, onLowMemory, onRebind, onStart, onTaskRemoved, onTimeout, onTrimMemory, onUnbind, startForeground, startForeground, stopForeground, stopForeground, stopSelf, stopSelf, stopSelfResult
Methods inherited from class android.content.ContextWrapper
bindIsolatedService, bindService, bindService, bindService, bindService, bindServiceAsUser, bindServiceAsUser, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingOrSelfUriPermissions, checkCallingPermission, checkCallingUriPermission, checkCallingUriPermissions, checkPermission, checkSelfPermission, checkUriPermission, checkUriPermission, checkUriPermissions, clearWallpaper, createAttributionContext, createConfigurationContext, createContext, createContextForSplit, createDeviceContext, createDeviceProtectedStorageContext, createDisplayContext, createPackageContext, createWindowContext, createWindowContext, databaseList, deleteDatabase, deleteFile, deleteSharedPreferences, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getAttributionSource, getAttributionTag, getBaseContext, getCacheDir, getClassLoader, getCodeCacheDir, getContentResolver, getDatabasePath, getDataDir, getDeviceId, getDir, getDisplay, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getFileStreamPath, getMainExecutor, getMainLooper, getNoBackupFilesDir, getObbDir, getObbDirs, getOpPackageName, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getParams, getResources, getSharedPreferences, getSystemService, getSystemServiceName, getTheme, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isDeviceProtectedStorage, isRestricted, isUiContext, moveDatabaseFrom, moveSharedPreferencesFrom, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerComponentCallbacks, registerDeviceIdChangeListener, registerReceiver, registerReceiver, registerReceiver, registerReceiver, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeSelfPermissionsOnKill, revokeUriPermission, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setTheme, setWallpaper, setWallpaper, startActivities, startActivities, startActivity, startActivity, startForegroundService, startInstrumentation, startIntentSender, startIntentSender, startService, stopService, unbindService, unregisterComponentCallbacks, unregisterDeviceIdChangeListener, unregisterReceiver, updateServiceGroup
Methods inherited from class android.content.Context
bindIsolatedService, getColor, getColorStateList, getDrawable, getString, getString, getSystemService, getText, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, revokeSelfPermissionOnKill, sendBroadcastWithMultiplePermissions
-
Constructor Details
-
PlayerService
public PlayerService()
-
-
Method Details