Intent Service

IntentService is a base class for Service
Which that handle asynchronous requests on demand.
Clients send requests through startService(Intent)
The service is started as needed, handles each Intent in turn using a worker thread
Stops itself when it runs out of work.

This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread.
The IntentService class exists to simplify this pattern and take care of the mechanics.
To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.on Request completion,the response is sent back to the activity via LocalBroadcastManager method.

How Intent Service work in Thread?

All requests are handled on a single worker thread
They may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.

Refernce code : https://github.com/kavidriod/IntentService_Oct10

Advertisements

Processes and Threads

Processes ?

Android operating system is built on Linux kernel,So Linux kernel process concepts are valid for android too.

When an app component start,and the application does not have any other components running,the android system initiate a new linux process for the application with a single thread of execution.This thread is called “Main Thread” .

To identify which processes should be removed or retained,The system places each processes into an “Importance Hierarchy”.The processed with the lowest importance are removed first.

Types ?

Active Processes,
Visible Processes,
Service Processes,
Background Processes,
Empty Processes,

Threads?

An android application automatically creates  a “main” thread when it starts.This is also called the UI thread.

UI thread is used for user interaction.All android applications runs on the UI main application thread.

Running all the components on a single thread will result in poor response time.

If UI thread is blocked for morethan 5 secs ,“Application Not Responding” dialog box will reveal.

Reason for ANR?

1.Doing Network operation.
2.Performing Long Calculation.
3.Accessing Database Operation on the UI thread.

Using Background Thread?

Android UI is not “Thread-Safe”.
Should not access UI operations on outside main thread or any other Thread.

Single Thread Model

1.Don’t block the UI thread – Long running operations should not perform on UI thread,It should be done in Worker thread.
2.Don’t access UI from outside main thread.Use “Message Passing” methods.

Message Passing?

To establish communication between main and worker thread,Android using message passing approach.

1.Handler : Handler object registers itself with the thread in which it is created.It provides a channel to send data to the thread.

2.Looper: It is a class which turns thread to pipeline thread.It implements the “loop” – It takes assigned task,execute it,then takes the next one,So on.
Use Looper class if you want to pass multiple messages.3.PNG

Worker Thread?

1.If you want to do long running back ground operation,you should make sure to do them in separate threads (“background” or “worker” threads).
2.You cannot update the UI from any thread other than the UI thread or the “main” thread.
3.To fix this problem, Android offers several ways to access the UI thread from other threads.

Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            // a potentially  time consuming task
            final Bitmap bitmap =
                    processBitMap("image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}


  1. The Above implementation is thread-safe.
  2. The background operation is done from a separate thread while the ImageView is always manipulated from the UI thread.
  3. However, as the complexity of the operation grows, this kind of code can get complicated and difficult to maintain.
  4. To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process messages delivered from the UI thread.
  5. The best solution, is to extend the AsyncTask class, which simplifies the execution of worker thread tasks that need to interact with the UI.

Android Service & Background Thread ?

For Long running operation you can use either background thread or Async Task

Background Thread:

1.Worker Thread,
2.Both UI and background thread runs Simultaneously.
3.Used for Performing Long running operations.

Android Service:

1.An application component.
2.Performs Long running operations in the background.
3.No user interface

Async Task

What is Async Task?

Async task performs Long running operations,publish results on the UI thread.

AsyncTask : This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

When to Use?

  • AsyncTasks should ideally be used for short operations (a few seconds at the most.)
  • If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as ExecutorThreadPoolExecutor and FutureTask.
  • AsyncTask must be subclassed to be used.
  • The subclass will override at least one method (doInBackground(Params...)),
  • most often will override a second one (onPostExecute(Result).)

Callbacks?

1.onPreExecute
2.doInBackground
3.onProgressUpdate
4.onPostExecute

4

Parameters Of Async Task:

There are three types of parameters are used for asynchronous task.

The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task for an execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

To mark a type as unused, simply use the type Void

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Method of Async Task:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task

  • A task can be cancelled at any time by invoking cancel(boolean).
  • Invoking this method will cause subsequent calls to isCancelled() to return true.
  • After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
  • To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically fromdoInBackground(Object[]), if possible (inside a loop for instance.)

Order of execution

  • When first introduced, AsyncTasks were executed serially on a single background thread.
  • Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel.
  • Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

How to  run AsyncTask Parallel?

If you want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Services

What is Service?

A Service is an application component,that perform some operations in the backgroud
It does not have user interface
An activity starts a service
Service can be started by component which belong to other application.

Service can perform

1.Downloading & Uploading file over network interface.
2.Play music in background.
3.File operations.

Types of Service?

1.Foreground

  • A foreground service performs some operation that is noticeable to the user.
  • For example, an audio app would use a foreground service to play an audio track.
  • Foreground services must display a status bar icon.
  • Foreground services continue running even when the user isn’t interacting with the app.

2.Background

  • A background service performs an operation that isn’t directly noticed by the user.
  • For example, if an app used a service to compact its storage, that would usually be a background service.

Note:
1.If your app targets API level 26 or higher, the system imposes restrictions on running background services.
2.when the app itself is not in the foreground. In most cases like this, your app should use a scheduled job instead.

3.Bounded.

It provides client-server interface.
It runs as long as other application component bound to it.
Multiple application component can be bind to a single service.
Service is destroyed when all application components are unBind.

How to create Service?

1.Must be declared in Android manifest.xml file
2. added as a child in tag
3.Attributes?
3.1.Enabled
3.2.Exported
3.3.Name
3.4.Permission
4.Defined service class should be the sub Class of Service
5.Override default methods in defined service class.

Reference : https://github.com/kavidriod/ServiceLifCycle