Tuesday, August 26, 2014

Services

Services run in the background without a dedicated GUI

Like Activities and Broadcast Receivers, they still execute in the main thread of the application’s process.

Started Services always have higher priority than inactive or invisible Activities

Android implements several Services, including the Location Manager, Media Controller, and Notification Manager

Summary

Methods to be overridden in a custom service

onBind()

The onBind() method enables you to bind an activity to a service.
This in turn enables an activity to directly access members and methods inside a service

onStartCommand()

The onStartCommand() method is called when you start the service explicitly using the startService() method
Returning the constant START_STICKY so that the service will continue to run until it is explicitly stopped

onDestroy()

The onDestroy() method is called when the service is stopped using the stopService() method

Making Service available to other applications

To make service available to other applications, you can always add an intent filter with an action name

<service android:name=”.MyService”>
    <intent-filter>
         <action android:name=”com.example.MyService” />
    </intent-filter>
</service>

Starting a service

Implicitly starting a service

startService(new Intent(getBaseContext(), MyService.class));

// Implicitly start a Service
Intent myIntent = new Intent(MyService.ORDER_PIZZA);
myIntent.putExtra("TOPPING", "Margherita");
startService(myIntent);

Explicitly starting a service

startService(new Intent(“com.example.MyService”));

// Explicitly start a Service
startService(new Intent(this, MyService.class));

If the Service requires permissions that your application does not have, the call to startService will throw a SecurityException.

Stopping a Service

stopService(new Intent(getBaseContext(), MyService.class)); 

Creating a Service

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
@Override
   public void onCreate() 
   {
      // TODO: Actions to perform when service is created.
   }

   @Override
   public IBinder onBind(Intent intent) 
   {
      // TODO: Replace with service binding implementation.
      return null;
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) 
   {
      // TODO Launch a background thread to do processing.
      return Service.START_STICKY;

   }
}

onStartCommand is called whenever the Service is started with a call to startService, so it may be executed several times within a Service’s lifetime.

Services are launched on the main Application thread, meaning that any processing done in the onStartCommand handler will happen on the main GUI thread

The standard pattern for implementing a Service is to create and run a new thread from onStartCommand to perform the processing in the background and stop the Service when it’s complete.

Service restart 

It returns a value that controls how the system will respond if the Service is restarted after being killed by the run time.

Control the restart behavior using one of the following Service constants

START_STICKY
START_NOT_STICKY
START_REDELIVER_INTENT

The restart mode you specify in your onStartCommand return value will affect the parameter values passed in to subsequent calls

Intent will be the parameter you passed in to startService to start your Service

After system-based restarts it will be either null, in the case of START_STICKY mode, or the original Intent, if the mode is set to START_REDELIVER_INTENT.

The flag parameter can be used to discover how the Service was started

START_FLAG_REDELIVERY
  • Indicates that the Intent parameter is a redelivery caused by the system run time’s having terminated the Service before it was explicitly stopped by a call to stopSelf

START_FLAG_RETRY
  • Indicates that the Service has been restarted after an abnormal termination. Passed in when the Service was previously set to START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
      if ((flags & START_FLAG_RETRY) == 0) {
            // TODO If it’s a restart, do something.
      }
      else {
            // TODO Alternative background process.
      }
      return Service.START_STICKY;
}

Registering a Service in the Manifest

<service android:enabled="true" android:name=".MyService"/>

Use the requires-permission attribute to require a uses-permission for other applications to access this Service

Self terminating a Service

stopSelf, either without a parameter to force a stop, or by passing in a startId value to insure processing
has been completed for each instance of startService called so far,

stopSelf(startId);


Example

public class ServiceActivity extends Activity {

    public void onClickStart(View view)
    {
    startService(new Intent(getBaseContext(), MyService.class));
    }
    
    public void onClickStop(View view)
    {
    stopService(new Intent(getBaseContext(), MyService.class));
    }
}

public class MyService extends Service 
{
@Override
public IBinder onBind(Intent arg0)
{
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//We want this service to continue running until it is explicitly stopped, so return sticky.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}

@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}    

AndroidManifest.xml

<application ..>
    <activity>
    </activity>
    <service android:name=".MyService" />
</application>

Synchronous Task (holds up the UI)

public int onStartCommand(Intent intent, int flags, int startId)
{
                        ...
int result = downloadFile(new URL("http://www.amazon.com/somefile.pdf"));
                        ...
}

private int downloadFile(URL url)
{
try
{
Thread.sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
return 100;
}

Asynchronous Task


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
new DoBackGroundTask().execute(new URL(
"http://www.amazon.com/somefiles.pdf"), new URL(
"http://www.wrox.com/somefiles.pdf"));
} catch (MalformedURLException e) {
e.printStackTrace();
         }

Repeated Tasks in a Service

You might also perform some repeated tasks in a service

For example, you may write an alarm clock service that runs persistently in the background. In this case, your service may need to periodically execute some code to check whether a prescheduled time has been reached so that an alarm can be sounded.

To execute a block of code to be executed at a regular time interval, you can use the Timer class within your service

int counter = 0;

static final int UPDATE_INTERVAL = 1000;
private Timer timer = new Timer();

public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.

doSomethingRepeatedly();
}

private void doSomethingRepeatedly()
{
TimerTask timerTask = new TimerTask()
{
public void run()
{
Log.d("MyService", String.valueOf(++counter));
}
};
timer.scheduleAtFixedRate(timerTask , 0, UPDATE_INTERVAL);
}
scheduleAtFixedRate(<task to run>, <time to wait before first execution>, <amount of time between subsequent exeuctions>)

Passing data from an Activity to a Service

In Activity

    public void startService(View view)
    {
    Intent intent = new Intent(getBaseContext(), MyService.class);
   
    try
    {
    URL[] urls = new URL[]
    {
    new URL("http://www.amazon.com/somefiles.gif"),
    new URL("http://www.wrox.com/somefiles.pdf"),
    new URL("http://www.google.com/somefiles.pdf")
    };
   
    intent.putExtra("URLs", urls);
    }catch(MalformedURLException e)
    {
    e.printStackTrace();
    }
   
    startService(intent);
    }

In Service

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.

Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

Object[] objURLs = (Object[]) intent.getExtras().get("URLs");
URL[] urls = new URL[objURLs.length];
for(int i = 0; i < urls.length; i++)
{
urls[i] = (URL) objURLs[i];
}

new DoBackGroundTask().execute(urls);
return START_STICKY;
}


No comments:

Post a Comment