9 services

43
SCHOOL OF ENGINEERING Activities 1 CE701 Mobile Computing Tejas Vasavada Android Services

Upload: ajayvorar

Post on 21-Aug-2015

44 views

Category:

Documents


0 download

TRANSCRIPT

SCHOOL OF ENGINEERING

Activities

1

CE701 Mobile Computing Tejas Vasavada

Android Services

Following are outcomes of this lecture:• Students will become aware of need of using

services.• Students will understand service life cycle.• Students will be able to create services on

their own.

Outcomes

• A Service is an application component that can perform long-running operations in the background.

• It does not provide a user interface. • Some application component can start a

service. Service will continue to run in the background even if the user switches to different application.

Service

• Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).

• A service can essentially take two forms:1) Started2) Bound

Started Service

• A service is called "started“ service if an application component (such as an activity) starts it by calling startService( ).

• A started service can be created in two ways:• By extending Service class• By extending IntentService class

Started Service

• If Service class is extended, service runs for indefinite time. It is destroyed only if activity destroys it using stopService( ) function.

• If IntentService class is extended, service is immediately destroyed once its task is completed.

• Service can destroy itself by calling stopSelf() method.

• Usually, a started service performs a single operation and does not return a result to the caller.

• For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

Bound Service

• A service is "bound" when an application component binds to it by calling bindService().

• A bound service offers a client-server interface that allows components to interact with the service, send requests and get results.

Bound Service

• A bound service runs only as long as at least one application component is bound to it.

• Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Examples

Example 1 [started service by extending Service class]Display two buttons on Screen : “START

METHOD” and “STOP METHOD”.When user clicks on “START METHOD”, service

should start. When user clicks on “STOP METHOD”, service should be stopped.

Two .java files should be present in your project:

• Service1Activity.java• MyService1.java.

public class Service1Activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startMethod(View v) { Intent i = new Intent(this,MyService1.class);

i.putExtra("message1","Hello to MyService1"); startService(i); }

Service1Activity.java

public void stopMethod(View v) {

Intent i = new Intent(this,MyService1.class); stopService(i);

}}

public class MyService1 extends Service {@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubToast.makeText(this, "Service Created",10).show();super.onCreate();}

MyService1.java

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stub String msg = intent.getStringExtra("message1"); Toast.makeText(this, "Service Started" + msg,10).show(); return super.onStartCommand(intent, flags, startId);} @Overridepublic void onDestroy() {// TODO Auto-generated method stub Toast.makeText(this, "Service Destroyed",10).show();super.onDestroy(); }} // end of class MyService1

• Service is started using startService(i) call. Intent i contains name of service class.

• When service is created, onCreate() method is called by system.

• Then onStartCommand() is called by system. • Service is not destroyed automatically.• stopService(i) destroys the service.

• When service is destroyed, onDestroy() method is called by system.

• Thus life cycle of Started service contains three callback methods: onCreate, onStartCommand() and onDestroy().

Example 2[started service by extending IntentService

class].• GUI is same as Example 1. • Implement service in demoIntentService.java.• Use same activity file. Make appropriate

changes in Activity file.

public class demoIntentService extends IntentService{public demoIntentService() {super("Intent Service");// TODO Auto-generated constructor stub}@Overrideprotected void onHandleIntent(Intent intent) {// TODO Auto-generated method stubString msg = intent.getStringExtra("message1");Toast.makeText(this, "onHandleIntent called" + msg, Toast.LENGTH_LONG).show();Log.d("handleIntent","it is called");}

demoIntentService.java

@Overridepublic void onCreate() {// TODO Auto-generated method stubToast.makeText(this, "onCreate called", Toast.LENGTH_LONG).show();super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubToast.makeText(this, "onStartCommand called", Toast.LENGTH_LONG).show();onHandleIntent(intent);super.onStartCommand(intent, flags, startId);

return 1;}@Overridepublic void onDestroy() {// TODO Auto-generated method stubToast.makeText(this, "onDestroy called", Toast.LENGTH_LONG).show();super.onDestroy();}}

• When service starts, onCreate() is called. Then onStartCommand().

• From onStartCommand(), onHandleIntent() is explicitly called.

• Service is destroyed on its own once onHandleIntent() is completed.

Example 3[Bound service by extending Service class].GUI has three buttons, “BIND SERVICE”,

“UNBIND SERVICE”, “FIND FACTORIAL”.One EditText control is present. User enters a

number in it. Then clicks on “FIND FACTORIAL”. Service finds factorial of given number.

public class Service2Activity extends Activity { /** Called when the activity is first created. */MyService mservice;boolean status;EditText number;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); number = (EditText)findViewById(R.id.editText1); }

Service2Activity.java

public void bindMethod(View v){ Intent intent = new Intent(this, MyService.class); bindService(intent, sc, Context.BIND_AUTO_CREATE); Toast.makeText(Service2Activity.this, "bindMethod called",Toast.LENGTH_LONG).show(); }

public void unbindMethod(View v){ unbindService(sc); status = false; Toast.makeText(Service2Activity.this, "unbindMethod called", Toast.LENGTH_LONG).show(); }

public void factorialMethod(View v) { if(status)

{int num,fact;num = Integer.parseInt(number.getText().toString());

fact = mservice.findFactorial(num); Toast.makeText(this,"Factorial is " +

fact,Toast.LENGTH_LONG).show(); } }

private ServiceConnection sc = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName arg0, IBinder arg1) {// TODO Auto-generated method stubToast.makeText(Service2Activity.this, "onServiceConnected started", Toast.LENGTH_LONG).show();LocalBinder binder = (LocalBinder)arg1;mservice = binder.getService();status = true;Toast.makeText(Service2Activity.this, "onServiceConnected completed", Toast.LENGTH_LONG).show();}

@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stub

status = false;Toast.makeText(Service2Activity.this, "onServiceDisConnected called", Toast.LENGTH_LONG).show();} }; // end of ServiceConnection class

} // end of Activity class

public class MyService extends Service {public final IBinder mbinder = new LocalBinder();@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubToast.makeText(this, "IBinder called", Toast.LENGTH_LONG).show();return mbinder;}public class LocalBinder extends Binder{public MyService getService(){Toast.makeText(MyService.this, "LocalBinder.getService() called", Toast.LENGTH_LONG).show();return MyService.this;}}

MyService.java

public int findFactorial(int x){int fact = 1;for(int i=1;i<=x;i++)

{fact = fact * I;}

return fact;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show();}

@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Toast.makeText(this,"Service Destroyed", Toast.LENGTH_LONG).show();}}

• When user clicks on “BIND SERVICE”, bindMethod() is called.

• In bindMethod(), bindService() is invoked. It is an in-built method.

• bindServie() contains following arguments: intent, service connection and flag.

• As next step, service is created if it is not running.

• When service is created, onCreate( ) is called. Then onBind() is called.

• Object returned by onBind() is stored in ‘arg1’ in onServiceConnected() method of ServiceConnection class.

• ‘arg1’ is assigned to ‘binder’ object in the same method.

• Then getService() method is called. Its return value is assigned to mservice object.

• mservice is object of MyService class.• When user clicks on “FindFactorial”,

findFactorial() method of MyService.java is called.

• Bound service created by above example is local to application.

• Second way of creating bound service is to use Messenger class.

• If Messenger class is used, service can be used by a component outside the application hosting the service.

• Find answer of following question yourself :

When onServiceDisconnected() is called ?

Example 4[bound service by using Messenger class].Activity sends a message to service. Service

receives the message and displays it.

Refer to service3.tar uploaded in edmodo for detailed code.

• Following files are uploaded in edmodo:• Service1.tar – for started service• Service2.tar – for bound service (example 3)• Service3.tar – for example 4

• We have discussed about started and bound services.

• Each of them can be created in two different ways.

• Services are different than Activities. They don’t have GUI.

Summary

• Website: developer.android.com• Chapter 21, Working with Services from

Android Wireless Application Development by Darcy and Conder

• Videos shared on FTP

Readings