1. Trang chủ
  2. » Giáo án - Bài giảng

Services for androi

30 228 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 30
Dung lượng 483,24 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Android CourseStarted service skeleton code public class ExampleService extends Service { int mStartMode; // indicates how to behave if the service is killed @Override public void onCre

Trang 1

Services

Trang 2

Android Course

Objectives

• After completing this module, you will be able to:

• Create, start, control, and interact with services such as started services, and bound services.

2

Trang 3

Android Course

Contents

• Services

• Started services

• The started service lifecycle

• The start mode

• Starting and stopping started services

• Bound services

• The bound service lifecycle

• The bound services skeleton code3

Trang 4

Android Course

Services

• A Service is an application component that can perform long-running operations in the background and does not provide a user interface

• Android supports the concept of a service for two reasons:

• First, to allow you to implement background tasks easily.

• Second, to allow you to do inter-process communication between applications running on the same device.

• These two reasons correspond to the two types of services that Android supports: started services and bound services

4

Trang 5

Android Course

Declaring a service in the manifest

<? xml version ="1.0" encoding = "utf-8" ?>

Trang 6

Android Course

Started Services

• Started services are services that are started via Context.startService() Once started, these types of services will continue to run until a client calls Context.stopService() on the service or the service itself calls stopSelf()

• Ex:

• It monitors sensor data from the device and does analysis, issues alerts if a certain condition is realized This service might run constantly.

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

6

Trang 7

onStartCommand() Called each time the

service is sent a command via startService().

onDestroy() Called as the service is

being shut down.

7

Trang 8

Android Course

Started service skeleton code

public class ExampleService extends Service { int mStartMode; // indicates how to behave if the service is killed @Override

public void onCreate() { // The service is being created

} @Override

public int onStartCommand( Intent intent, int flags, int startId) { // The service is starting, due to a call to startService()

return mStartMode;

}

@Override

public IBinder onBind( Intent intent) {

// We don't provide binding, so return null return null ;

} @Override

public void onDestroy() {

// The service is no longer used and is being destroyed

8

start mode

started service form

Trang 9

• START_STICKY:

• If the system kills the service after onStartCommand() returns, recreate

the service and call onStartCommand() , but do not redeliver the last intent Instead, the system calls onStartCommand() with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered This is suitable for media players (or similar

services) that are not executing commands , but running indefinitely and waiting for a job.

• START_REDELIVER_INTENT:

• If the system kills the service after onStartCommand() returns, recreate

the service and call onStartCommand() with the last intent that was delivered to the service Any pending intents are delivered in turn This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file

9

Trang 10

• using stopSelft() methods of Service class

• using stopService() methods of Context class (ex: Activity class)

Intent intent = new Intent (this, ExampleService class );

stopService(intent);

10

Trang 11

public int onStartCommand(Intent intent, int flags, int startId) {

super onStartCommand(intent, flags, startId);

Log.i( "<<SimpleService-onStart>>" , "I did something" );

Trang 12

Android Course

SimpleService example

12

Starting SimpleService:

Stopping SimpleService:

Trang 13

Android Course

StopSelfService example

public class StopSelfService extends Service {

private Looper mServiceLooper ;

private ServiceHandler mServiceHandler ;

// Handler that receives messages from the thread

@Override

public IBinder onBind(Intent intent) {

// We don't provide binding, so return null

return null ;

} @Override

public void onDestroy() {

Toast.makeText(getApplicationContext(), "service done" ,

Toast.LENGTH_SHORT).show();

// Log.i("<<StopSelfService-onDestroy>>", "Service done!");

} 13

started service form

Trang 14

Android Course

StopSelfService example

@Override

public void onCreate() {

// Start up the thread running the service Note that we create a // separate thread because the service normally runs in the

// process's main thread, which we don't want to block We also // make it background priority so CPU-intensive work will not // disrupt our UI.

HandlerThread thread = new HandlerThread( "ServiceStartArguments" ,

Trang 15

Android Course

StopSelfService example

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Toast.makeText( this , "service starting", Toast LENGTH_SHORT ).show();

// For each start request, send a message to start a job and // deliver the start ID so we know which request we're

// stopping when we finish the job

Message msg = mServiceHandler obtainMessage();

Trang 16

Android Course

StopSelfService example: ServiceHandler inner class

private final class ServiceHandler extends Handler {

public ServiceHandler(Looper looper) {

super (looper);

}

@Override

public void handleMessage(Message msg) {

// Normally we would do some work here, like download a file.

// For our sample, we just sleep for 5 seconds.

long endTime = System.currentTimeMillis() + 5 * 1000;

while (System.currentTimeMillis() < endTime) {

Trang 17

• A bound service runs only as long as another 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

17

Trang 18

onBind() Called when a client is

binding to the service with bindService()

onUnbind() Called when all clients

have unbound with unbindService() 18

Trang 19

Android Course

BoundService example

public class BoundService extends Service {

// Binder given to clients

private final IBinder mBinder = new LocalBinder();

// Random number generator

private final Random mGenerator = new Random();

@Override

public IBinder onBind(Intent intent) {

return mBinder ;

}

/** method for clients */

public int getRandomNumber() {

return mGenerator nextInt(100);

}

// LocalBinder inner class

} 19

Bound service form

Trang 20

Android Course

BoundService example: LocalBinder inner class

/**

* Class used for the client Binder Because we know this service

* always runs in the same process as its clients, we don't need

* to deal with IPC.

20

Trang 21

Android Course

Calling BoundService from an Activity

public class BoundServiceDemoActivity extends Activity {

private BoundService mService ;

private boolean mBound = false ;

/** Defines callbacks for service binding, passed to bindService() */

private ServiceConnection mConnection = new ServiceConnection() {

public void onServiceDisconnected (ComponentName arg0) {

} };

21

Trang 22

Intent intent = new Intent( this , BoundService class );

bindService(intent, mConnection , Context.BIND_AUTO_CREATE);

Trang 23

// Call a method from the LocalService.

// However, if this call were something that might hang, then // this request should occur in a separate thread to avoid // slowing down the activity performance.

int num = mService getRandomNumber();

Toast.makeText( this , "number: " + num, Toast LENGTH_SHORT ).show();

} }

23

Trang 25

Android Course

Questions or Discussions

• What is the difference between started and bound

service form?

• In which case do we use started services?

• In which case do we use bound services?25

Trang 26

Android Course

References & Further Readings

• Creating a simple started service by extending the IntenService class

• http://

developer.android.com/guide/topics/fundamentals/services.html#Exte ndingIntentService

• Using a Messenger to perform inter-process communication (IPC) without the need to use AIDL

• http://

developer.android.com/guide/topics/fundamentals/bound-services.htm l#Messenger

26

Trang 27

Android Course

References & Further readings

• Professional Android 2 Application Development, Reto

Meier, Wiley Publishing (2010)

• Introducing Services, Chapter 9 27

Trang 28

Android Course

References & Further Readings

• Beginning Android 3, Mark

Murphy, Apress Publishing

(2011)

• Services: The Theory, Chapter 35 28

Trang 29

Android Course

References & Further Readings

• Pro Android 3, Mark Murphy,

Apress Publishing (2011)

• Understanding Android Services, Chapter 11

29

Trang 30

Android Course

References & Further Readings

Conder, Lauren Darcey,

Addison-Wesley Professional Publishing (2010)

• Working with Services, Chapter 21

30

Ngày đăng: 02/02/2015, 11:13

TỪ KHÓA LIÊN QUAN