Running in Background Flashcards
The main thread
Independent path of execution in a running program
Code is executed line by line
App runs on Java thread called “main” or “UI thread”
Draws UI on the screen
Responds to user actions by handling UI events
Two rules for Android threads
- Do not block the UI thread. The Main thread must be fast
Complete all work in less than 16 ms for each screen
Run slow non-UI work on a non-UI thread
If the UI waits too long for an operation to finish, it becomes unresponsive
The framework shows an Application Not Responding (ANR) dialog
- Do not access the Android UI toolkit from outside
the UI thread
Do UI work only on the UI thread
Background threads
Execute long running tasks on a background thread
AsyncTask
The Loader Framework
Services
AsyncTask
Use AsyncTask to implement basic background tasks
Override two methods:
doInBackground()—runs on a background thread
All the work to happen in the background
onPostExecute()—runs on main thread when work done
Process results
Publish results to the UI
onPreExecute()
Runs on the main thread
Sets up the task
onProgressUpdate()
Runs on the main thread receives calls from
publishProgress() from background thread
Limitations of AsyncTask
When device configuration changes, Activity is destroyed
AsyncTask cannot connect to Activity anymore
New AsyncTask created for every config change
Old AsyncTasks stay around
App may run out of memory or crash
When to use AsyncTask
Short or interruptible tasks
Tasks that do not need to report back to UI or user
Lower priority tasks that can be left unfinished
Use AsyncTaskLoader otherwise
Loader
Provides asynchronous loading of data from a content provider or other data source
BENEFITS:
- Reconnects to Activity after configuration change. LoaderManager handles configuration changes for you
- Callbacks implemented in Activity
- Can monitor changes in data source and deliver new data
Many types of loaders available:
CursorLoader - data from a ContentProvider
Loader or AsyncTaskLoader - to load data from some other source
LoaderManager
Manages one or more Loader instances
getSupportLoaderManager().initLoader(0, null, this);
To start loading data from a loader, call either initLoader() or restartLoader(). The system automatically determines whether a loader with the same integer ID already exists and will either create a new loader or reuse an existing loader.
AsyncTaskLoader
A Loader subclass, used to load data from a data source.
DIFERENCESE with ASYNTASK :
doInBackground() loadInBackground()
onPostExecute() onLoadFinished()
Steps for AsyncTaskLoader subclass
1) Subclass AsyncTaskLoader
2) Implement constructor - to call super()
3) loadInBackground()
4) onStartLoading() - When restartLoader() or initLoader() is called, the LoaderManager invokes the onStartLoading() callback
Implement loader callbacks in Activity
onCreateLoader()
onLoadFinished()
onLoaderReset()
1) onCreateLoader() — Create and return a new Loader for the given ID: @Override public Loader> onCreateLoader(int id, Bundle args) { return new StringListLoader(this,args.getString("queryString")); }
2)onLoadFinished() — Called when a previously created loader has finished its load. Results of loadInBackground() are passed to onLoadFinished() where you can display them
3) onLoaderReset() — Called when a previously created loader is being reset making its data unavailable
Only called when loader is destroyed
Leave blank most of the time
broadcast
— Broadcast are send using Implicit Intents : sendBroadcast() method—asynchronous
sendOrderedBroadcast()—synchronously
- –Can be received by any application registered for the intent
- – Used to notify all apps of an event
broadcast receiver
——Listens for incoming intents sent by sendBroadcast().(.from In the background)
—–Intents can be sent
> By the system, when an event occurs that might change the behavior of an app
> By another application, including your own
Broadcast receiver always responds
Responds even when your app is closed
Independent from any activity
When a broadcast intent is received and delivered to onReceive(), it has 5 seconds to execute, and then the receiver is destroyed
Steps for creating a broadcast receiver
Subclass BroadcastReceiver
Implement onReceive() method
Register to receive broadcast
Statically, in AndroidManifest
Dynamically, with registerReceiver()
registerReceiver(mReceiver, mIntentFilter)
Controlling permission sender
Other apps can send broadcasts to your receiver—use permissions to control this
void sendBroadcast (Intent intent, String receiverPermission)
Receivers must request permission with in AndroidManifest.xml
Controlling permission receiver
Other apps can respond to broadcast your app sends
registerReceiver(BroadcastReceiver,
IntentFilter, String, android.os.Handler)
or in tag
Senders must request permission with in AndroidManifest.xml
Local Broadcast Manager
For broadcasts only in your app
No security issues since no cross-app communication
LocalBroadcastManager.sendBroadcast()
LocalBroadcastManager.registerReceiver()
Service
A Service is an application component that can perform long-running operations in the background and does not provide a user interface
What are services good for?
Network transactions
Play music
Perform file I/O
Interact with a content provider
Characteristics of services
Started with an Intent
Can stay running when user switches applications
Lifecycle—which you must manage
Other apps can use the service—manage permissions
Runs in the main thread of its hosting process
Forms of services: started
Started with startService()
Runs indefinitely until it stops itself
Usually does not update the UI
Forms of services: bound
Offers a client-server interface that allows components to interact with the service
Clients send requests and get results
Started with bindService() with an explicit Intent
Ends when all clients unbind
Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
Creating a service
Manage permissions
Subclass IntentService or Service class
Implement lifecycle methods
Start service from activity
Make sure service is stoppable
Stopping a service
A started service
A bound service
IntentService
A started service must manage its own lifecycle
If not stopped, will keep running and consuming resources
The service must stop itself by calling stopSelf()
Another component can stop it by calling stopService()
Bound service is destroyed when all clients unbound
IntentService is destroyed after onHandleIntent() returns
IntentService
Simple service with simplified lifecycle
Uses worker threads to fulfill requests
Stops itself when done
Ideal for one long task on a single background thread
IntentService Limitations
Cannot interact with the UI
Can only run one request at a time
Cannot be interrupted
What is Job Scheduler
Used for intelligent scheduling of background tasks
Job Scheduler components
JobService—Service class where the task is initiated
JobInfo—Builder pattern to set the conditions for the task
JobScheduler—Schedule and cancel tasks, launch service
JobService
Runs on the main thread
JobService subclass
Override
»_space; onStartJob() –Implement work to be done here.
Called by system when conditions are met
»_space; onStopJob() –Called if system has determined execution of job must stop… because requirements specified no longer met
JobScheduler - Scheduling the job
Obtain a JobScheduler object form the system Call schedule() on JobScheduler, with JobInfo object