com.octo.android.robospice
Class SpiceService

java.lang.Object
  extended by android.content.Context
      extended by android.content.ContextWrapper
          extended by android.app.Service
              extended by com.octo.android.robospice.SpiceService
All Implemented Interfaces:
android.content.ComponentCallbacks, android.content.ComponentCallbacks2
Direct Known Subclasses:
BitmapSpiceService, GoogleHttpClientSpiceService, com.octo.android.robospice.okhttp.OkHttpSpiceService, RetrofitSpiceService, SpringAndroidSpiceService, UncachedSpiceService

public abstract class SpiceService
extends android.app.Service

This is an abstract class used to manage the cache and provide web service result to an activity.
Extends this class to provide a service able to load content from web service or cache (if available and enabled). You will have to implement createCacheManager(Application) to configure the CacheManager used by all requests to persist their results in the cache (and load them from cache if possible).

Author:
jva, mwa, sni

Nested Class Summary
protected  class SpiceService.SelfStopperRequestProcessorListener
           
static class SpiceService.SpiceServiceBinder
           
 
Field Summary
protected static int DEFAULT_NOTIFICATION_ID
           
protected static int DEFAULT_THREAD_COUNT
           
protected static int DEFAULT_THREAD_KEEP_ALIVE_TIME
          Default in TimeUnit.NANOSECONDS implies core threads are not disposed when idle.
protected static int DEFAULT_THREAD_PRIORITY
           
 
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
 
Fields inherited from class android.content.Context
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, AUDIO_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_WAIVE_PRIORITY, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESTRICTED, DEVICE_POLICY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, KEYGUARD_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MEDIA_ROUTER_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, POWER_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, STORAGE_SERVICE, TELEPHONY_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, UI_MODE_SERVICE, USB_SERVICE, VIBRATOR_SERVICE, WALLPAPER_SERVICE, WIFI_P2P_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
SpiceService()
          Default constructor.
 
Method Summary
 void addRequest(CachedSpiceRequest<?> request, Set<RequestListener<?>> listRequestListener)
           
 void addSpiceServiceListener(SpiceServiceListener spiceServiceListener)
           
abstract  CacheManager createCacheManager(android.app.Application application)
           
 android.app.Notification createDefaultNotification()
          This method can be overriden in order to create a foreground SpiceService.
protected  RequestProcessor createRequestProcessor(CacheManager cacheManager, RequestProgressManager requestProgressManager, RequestRunner requestRunner)
          Factory method to create an entity responsible for processing requests send to the SpiceService.
protected  RequestProcessorListener createRequestProcessorListener()
          Creates a SpiceService.SelfStopperRequestProcessorListener for the RequestProcessor used by this service.
protected  RequestListenerNotifier createRequestRequestListenerNotifier()
          Method to create a Request Progress Reporter object which is responsible for informing the listeners of the current state of each request.
protected  SpiceServiceListenerNotifier createSpiceServiceListenerNotifier()
          Creates the SpiceServiceListenerNotifier.
 void dontNotifyRequestListenersForRequest(CachedSpiceRequest<?> request, Collection<RequestListener<?>> listRequestListener)
           
 void dumpState()
           
<T> List<Object>
getAllCacheKeys(Class<T> clazz)
           
 int getCoreThreadCount()
          Override this method to increase the number of core threads used to process requests.
<T> T
getDataFromCache(Class<T> clazz, Object cacheKey)
           
 Date getDateOfDataInCache(Class<?> clazz, Object cacheKey)
           
protected  ExecutorService getExecutorService()
          Factory method to create an ExecutorService that will be used to execute requests.
 int getKeepAliveTime()
          Override this method to set the keep alive time for core threads getExecutorService().
 int getMaximumThreadCount()
          Override this method to increase the number of maximum threads used to process requests.
protected  NetworkStateChecker getNetworkStateChecker()
          Factory method to create an entity responsible to check for network state.
protected  int getNotificationId()
           
protected  RequestProcessor getRequestProcessor()
          For testing purposes only.
 int getThreadCount()
          Override this method to increase the number of threads used to process requests.
 int getThreadPriority()
          Override this method to change the priority of threads requests.
 boolean isCoreThreadDisposable()
          Override this method to disable timeout on core threads.
 boolean isCreated()
           
 boolean isDataInCache(Class<?> clazz, Object cacheKey, long cacheExpiryDuration)
           
 boolean isFailOnCacheError()
           
<T> List<T>
loadAllDataFromCache(Class<T> clazz)
           
 android.os.IBinder onBind(android.content.Intent intent)
           
 void onCreate()
           
 void onDestroy()
           
 void onRebind(android.content.Intent intent)
           
 int onStartCommand(android.content.Intent intent, int flags, int startId)
           
 boolean onUnbind(android.content.Intent intent)
           
<T> T
putDataInCache(Object cacheKey, T data)
           
 void removeAllDataFromCache()
           
 void removeAllDataFromCache(Class<?> clazz)
           
 boolean removeDataFromCache(Class<?> clazz, Object cacheKey)
           
 void removeSpiceServiceListener(SpiceServiceListener spiceServiceListener)
           
 void setFailOnCacheError(boolean failOnCacheError)
           
static void setIsJunit(boolean b)
           
 
Methods inherited from class android.app.Service
dump, getApplication, onConfigurationChanged, onLowMemory, onStart, onTaskRemoved, onTrimMemory, startForeground, stopForeground, stopSelf, stopSelf, stopSelfResult
 
Methods inherited from class android.content.ContextWrapper
attachBaseContext, bindService, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkUriPermission, checkUriPermission, clearWallpaper, createPackageContext, databaseList, deleteDatabase, deleteFile, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getBaseContext, getCacheDir, getClassLoader, getContentResolver, getDatabasePath, getDir, getExternalCacheDir, getExternalFilesDir, getFilesDir, getFileStreamPath, getMainLooper, getObbDir, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getResources, getSharedPreferences, getSystemService, getTheme, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isRestricted, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, removeStickyBroadcast, revokeUriPermission, sendBroadcast, sendBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendStickyBroadcast, sendStickyOrderedBroadcast, setTheme, setWallpaper, setWallpaper, startActivities, startActivities, startActivity, startActivity, startInstrumentation, startIntentSender, startIntentSender, startService, stopService, unbindService, unregisterReceiver
 
Methods inherited from class android.content.Context
getString, getString, getText, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, registerComponentCallbacks, unregisterComponentCallbacks
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_NOTIFICATION_ID

protected static final int DEFAULT_NOTIFICATION_ID
See Also:
Constant Field Values

DEFAULT_THREAD_COUNT

protected static final int DEFAULT_THREAD_COUNT
See Also:
Constant Field Values

DEFAULT_THREAD_PRIORITY

protected static final int DEFAULT_THREAD_PRIORITY
See Also:
Constant Field Values

DEFAULT_THREAD_KEEP_ALIVE_TIME

protected static final int DEFAULT_THREAD_KEEP_ALIVE_TIME
Default in TimeUnit.NANOSECONDS implies core threads are not disposed when idle.

See Also:
Constant Field Values
Constructor Detail

SpiceService

public SpiceService()
Default constructor.

Method Detail

onCreate

public void onCreate()
Overrides:
onCreate in class android.app.Service

isCreated

public boolean isCreated()

onStartCommand

public int onStartCommand(android.content.Intent intent,
                          int flags,
                          int startId)
Overrides:
onStartCommand in class android.app.Service

createRequestProcessor

protected RequestProcessor createRequestProcessor(CacheManager cacheManager,
                                                  RequestProgressManager requestProgressManager,
                                                  RequestRunner requestRunner)
Factory method to create an entity responsible for processing requests send to the SpiceService. The default implementation of this method will return a RequestProcessor. Override this method if you want to inject a custom request processor. This feature has been implemented following a request from Christopher Jenkins.

Parameters:
cacheManager - the cache manager used by this service.
requestProgressManager - will notify of requests progress.
requestRunner - executes requests.
Returns:
a RequestProcessor that will be used to process requests.

createRequestProcessorListener

protected RequestProcessorListener createRequestProcessorListener()
Creates a SpiceService.SelfStopperRequestProcessorListener for the RequestProcessor used by this service. See a typical implementation : @see SpiceService.SelfStopperRequestProcessorListener.

Returns:
a new instance SpiceService.SelfStopperRequestProcessorListener for the RequestProcessor used by this service.

getRequestProcessor

protected RequestProcessor getRequestProcessor()
For testing purposes only.

Returns:
the request processor of this spice service.

createRequestRequestListenerNotifier

protected RequestListenerNotifier createRequestRequestListenerNotifier()
Method to create a Request Progress Reporter object which is responsible for informing the listeners of the current state of each request. You can use this method to modify the existing behavior

Returns:
RequestListenerNotifier

getNetworkStateChecker

protected NetworkStateChecker getNetworkStateChecker()
Factory method to create an entity responsible to check for network state. The default implementation of this method will return a DefaultNetworkStateChecker. Override this method if you want to inject a custom network state for testing or to adapt to connectivity changes on the Android. This method is also useful to create non-network related requests. In that case create a NetworkStateChecker that always return true. This feature has been implemented following a request from Pierre Durand.

Returns:
a NetworkStateChecker that will be used to determine if network state allows requests executions.

getExecutorService

protected ExecutorService getExecutorService()
Factory method to create an ExecutorService that will be used to execute requests. The default implementation of this method will create a single threaded or multi-threaded ExecutorService depending on the number of threads returned by getThreadCount() and will assign them the priority returned by getThreadPriority().

If you override this method in your service, you can supply a custom ExecutorService.

This feature has been implemented following a request from Riccardo Ciovati.

Returns:
the ExecutorService to be used to execute requests .

createSpiceServiceListenerNotifier

protected SpiceServiceListenerNotifier createSpiceServiceListenerNotifier()
Creates the SpiceServiceListenerNotifier.

Returns:
SpiceServiceListenerNotifier

createDefaultNotification

public android.app.Notification createDefaultNotification()
This method can be overriden in order to create a foreground SpiceService. By default, it will create a notification that can be used to set a spiceService to foreground (depending on the versions of Android, the behavior is different : before ICS, no notification is shown, on ICS+, a notification is shown with app icon). On Jelly Bean+, the notifiation only appears when notification bar is expanded / pulled down.

Returns:
a notification used to tell user that the SpiceService is still running and processing requests.

getNotificationId

protected int getNotificationId()

onDestroy

public void onDestroy()
Overrides:
onDestroy in class android.app.Service

createCacheManager

public abstract CacheManager createCacheManager(android.app.Application application)
                                         throws CacheCreationException
Throws:
CacheCreationException

getThreadCount

public int getThreadCount()
Override this method to increase the number of threads used to process requests. This method will have no effect if you override getExecutorService().

Returns:
the number of threads used to process requests. Defaults to DEFAULT_THREAD_COUNT.

getCoreThreadCount

public int getCoreThreadCount()
Override this method to increase the number of core threads used to process requests. This method will have no effect if you override getExecutorService().

Returns:
the number of threads used to process requests. Defaults to DEFAULT_THREAD_COUNT.

getMaximumThreadCount

public int getMaximumThreadCount()
Override this method to increase the number of maximum threads used to process requests. This method will have no effect if you override getExecutorService().

Returns:
the number of threads used to process requests. Defaults to DEFAULT_THREAD_COUNT.

getKeepAliveTime

public int getKeepAliveTime()
Override this method to set the keep alive time for core threads getExecutorService().

Returns:
the time to keep alive idle threads on TimeUnit.NANOSECONDS. Defaults to DEFAULT_THREAD_KEEP_ALIVE_TIME.

isCoreThreadDisposable

public boolean isCoreThreadDisposable()
Override this method to disable timeout on core threads. This is only taken into consideration for Android SDK 9+. getExecutorService().

Returns:
whether core threads are disposable or not (DEFAULT=true).

getThreadPriority

public int getThreadPriority()
Override this method to change the priority of threads requests. This method will have no effect if you override getExecutorService().

Returns:
the number of threads used to process requests.Defaults to DEFAULT_THREAD_PRIORITY.

addRequest

public void addRequest(CachedSpiceRequest<?> request,
                       Set<RequestListener<?>> listRequestListener)

removeDataFromCache

public boolean removeDataFromCache(Class<?> clazz,
                                   Object cacheKey)

removeAllDataFromCache

public void removeAllDataFromCache(Class<?> clazz)

getAllCacheKeys

public <T> List<Object> getAllCacheKeys(Class<T> clazz)

loadAllDataFromCache

public <T> List<T> loadAllDataFromCache(Class<T> clazz)
                             throws CacheLoadingException,
                                    CacheCreationException
Throws:
CacheLoadingException
CacheCreationException

getDataFromCache

public <T> T getDataFromCache(Class<T> clazz,
                              Object cacheKey)
                   throws CacheLoadingException,
                          CacheCreationException
Throws:
CacheLoadingException
CacheCreationException

putDataInCache

public <T> T putDataInCache(Object cacheKey,
                            T data)
                 throws CacheSavingException,
                        CacheCreationException
Throws:
CacheSavingException
CacheCreationException

isDataInCache

public boolean isDataInCache(Class<?> clazz,
                             Object cacheKey,
                             long cacheExpiryDuration)
                      throws CacheCreationException
Throws:
CacheCreationException

getDateOfDataInCache

public Date getDateOfDataInCache(Class<?> clazz,
                                 Object cacheKey)
                          throws CacheLoadingException,
                                 CacheCreationException
Throws:
CacheLoadingException
CacheCreationException

removeAllDataFromCache

public void removeAllDataFromCache()

isFailOnCacheError

public boolean isFailOnCacheError()

setFailOnCacheError

public void setFailOnCacheError(boolean failOnCacheError)

dontNotifyRequestListenersForRequest

public void dontNotifyRequestListenersForRequest(CachedSpiceRequest<?> request,
                                                 Collection<RequestListener<?>> listRequestListener)

onBind

public android.os.IBinder onBind(android.content.Intent intent)
Specified by:
onBind in class android.app.Service

onRebind

public void onRebind(android.content.Intent intent)
Overrides:
onRebind in class android.app.Service

onUnbind

public boolean onUnbind(android.content.Intent intent)
Overrides:
onUnbind in class android.app.Service

dumpState

public void dumpState()

addSpiceServiceListener

public void addSpiceServiceListener(SpiceServiceListener spiceServiceListener)

removeSpiceServiceListener

public void removeSpiceServiceListener(SpiceServiceListener spiceServiceListener)

setIsJunit

public static final void setIsJunit(boolean b)


Copyright © 2012-2014. All Rights Reserved.