Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2074457
  • 博文数量: 413
  • 博客积分: 10926
  • 博客等级: 上将
  • 技术积分: 3862
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 18:14
文章分类

全部博文(413)

文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(6)

2011年(138)

2010年(85)

2009年(42)

2008年(46)

2007年(26)

2006年(59)

分类: LINUX

2010-11-04 16:47:08

  1. Docs
    • Services Fundamentals
      http://developer.android.com/guide/topics/fundamentals/services.html
    • Bind Services (3 types: Binder, Messenger, AIDL)
      http://developer.android.com/guide/topics/fundamentals/bound-services.html
    • AIDL & Parcelable
      http://developer.android.com/guide/developing/tools/aidl.html
    • Service Class
      http://developer.android.com/reference/android/app/Service.html
    • xxx
  2. Classes
    A service is a component that runs in the background to perform long-running operations or to perform work for remote processes or for components of other applications. A service does not provide a user interface.

    By default, a services runs in the same process as the application in which it is declared and in the main thread of that application.
    • Service
      This is the base class for all services.
    • IntentService
      Handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

      Sample:

      //Implement IntentService
      public class MyService extends IntentService {



      public MyService() {
          super("xxxx");
      }

      public MyService(String name) {
          super(name);
          // TODO Auto-generated constructor stub
      }
      @Override
      protected void onHandleIntent(Intent arg0) {
          // TODO Auto-generated method stub
          for (long i = 0; i <= 1000000; i++) {
              Log.e("Service Example", " " + i);
              try {
                  Thread.sleep(700);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }


      //Send request
      public void onclick(View view) {
      Intent svc = new Intent(this, MyService.class);
          startService(svc);
      }

    • xxx
  3. Basic
    1. Start/Stop Service
      1. startService/stopService
        Clients need not to interact with service
      2. bindService/unbindService
        Clients need to communicate with service. You can bind to a service that was already started with startService(), in cases like this, stopService() or stopSelf() does not actually stop the service until all clients unbind.
        If you start service with bindService, the stopSelf invoked in Service won't cause the service to be destroyed if there is still some service connection existing.
      3. stopSelf   // Stop self invoked within Service
      4. xxx
    2. Local Service
      This type of service is private to your own application, and runs in the same process as the client.
      1. Communication manner: Binder
      2. Activity and service can access data and call methods of each other.
        If you want service to notify activity once the specific event takes place, you can implement this feature with classic Observer design pattern:
         - declare an interface in service,
         - implement the interface in activity,
         - create an instance of interface implementation, and then set it to service
         - service invokes the methods of the interface when the specific event takes place.
    3. Remote Messenger Service
      This type of service works across differet process through Messenger which is implemented with AIDL. Such service doesn't perform multi-threading, that means Messenger allows the service to handle one call at a time because Messenger queues all calls to the service (The calls to the service will send message to handler of service); If you want to handle multi-threading, you must use AIDL directly.
      1. Communication manner:  Messenger + Handler + Bundle + Parcelable + Parcel
      2. If clients need to get response from Service, clients need to define its-own Handler, i.e.:
        m_messengerService = new Messemger(service); //Create a messenger instance of service, invoked in ServiceConnection.onServiceConnected();

        ......

        m_messengerClient = new Messenger(new ClientHandler()); //Create a messenger instance of client, invoked at proper place.

        ..............
        Message msgSent = Message.obtain(null, xxx);
        msgSent.replyTo = messengerClient;
        messengerService.send(msg); //Then Service can reply data to the clients by invoking msgReceived.replyTo.send(xxx) in Service's handler.
      3. You can pass primitive data directly between service and clients, such as int, byte, long etc. But if you need to pass objects, the class of object need to implement interfaces declared in Parcelable as following (http://developer.android.com/guide/developing/tools/aidl.html#Calling):
        • Define class to implement Parcelable
          Notes:
          - Implement Parcelable class, such as MyRect.java
          - Create .aidl file, such MyRect.aidl
           (Sample: file:///D:/Program%20Files/Android/android-sdk-windows/docs/guide/developing/tools/aidl.html#PassingObjects)
        • Send message containing objects to remote process
          Message msg = Message.obtain(null, xxx);
          msg.getData().putParcelable(key, parcelable_obj);
          messenger.send(msg);
        • Receive message containing objects from remote process
          Bundle bundle = msg.getData();
          bundle.setClassLoader(context.getClassLoader());  //Necessary, but it need not to be invoked when to send message
          parcelable_obj = bundle.get(key);
        • xxx
      4. xxx
    4. Remote AIDL Service
      This type of service works across differet process, and allow different application to access your service for IPC, that means a single service can serve for multiple applications, the applications share the same data(s) of the service. AIDL is used to define the programming interface that both clients and service agree upon in order to commnicate with each other. AIDL interface are direct function calls, you should not make assumptions about the thread in which the call occurs.

      be aware that calls to an AIDL interface are direct function calls (that means these functions can be invoked within multiple thread (in multiple process) simultaneously). An implementation of an AIDL interface must be completely thread-safe.
      1. Communication manner: AIDL
      2. Implementation
        1. Create an .aidl file in the sub-directory of /src, after build, a file with the same name as .aidl but the postfix is changed to .java is generated under /gen.
          You must include an import statement for each additional type not supported for AIDL, even if they are defined in the same package as your interface.
        2. Implement the intefaces declared in .aidl, generally you need to implement it within Service sub-class.
          - invoking for the interfaces is not guaranteed to be executed on the main thread, so you need to think about multithreading from the start and properly build your service to be thread-safe.
          - RPC calls are synchronous. If you know that the service takes more than a few milliseconds to complete a request, you should not call it from the activity's main thread.
          - No exceptions that you throw are sent back to the caller
        3. Exporse the interfaces to clients
      3. FAQ
        1. [Q] Report error "couldn't find import for class" when to build .aidl project.
          [A] Forgot to add .aidl for Parcelable sub-class:
          package xxx;
          parcelable
          (From: http://blog.csdn.net/ghd2000/archive/2010/12/17/6082339.aspx)
      4. xxx
    5. start/bind service of other application
      ComponentName component = new ComponentName("com.mycompony.product","com.mycompony.product.myclass");                  
      Intent intent = new Intent();
      intent.setComponent(component); 
      bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
    6. xxx
  4. Interfaces of Service
    • onBind
      This interface will be invoked if you start service via Context.bindService.
    • onStart
      If you start service with startService no matter if the service is running, this interface will be invoked.
      onStart is available in old sdk, and it is deprecated from sdk 2.0, and replaced with onStartCommand. If you want to write compatible source code, you must implement those two interfaces.
    • onStartCommand
      1. Intro
        If you start service with startService no matter if the service is running, this interface will be invoked.
      2. The parameters "Intent intent"
        If you start service with startService, intent != null;
        If the service is restarted by Android system, such as after application is killed, intent == null;
      3. The return value
        If you want Android system to restart your application once it is killed, return START_STICK (1), otherwise, you can return START_NO_STICK (2)
      4. xxx
    • xxx
  5. ServiceConnection Interface
    You must define a flag to indicate if the service is bound or not, then you can determine whether to unbind the service according to this flag. (Please see 'boolean mBound;' at http://developer.android.com/guide/topics/fundamentals/bound-services.html)
    1. onServiceConnected
      This interface will be invoked once connection is established.
    2. onServiceDisconnected
      If service is killed (or is aborted), this interface will be invoked. But if the service is destroyed normally (such as via invoking stopSelf), this interface won't be invoked.
    3. xxx
  6. How to Start
    1. startService
    2. bindService
      If service is started by invoking Context.bindService, it will be destroyed automatically if no one is binded with it (invok Context.unbindService to unbind service); If you want to avoid this, you can invoke startService before bindService.
    3. xxx
  7. Start a service of other application
    When the system starts a component of other application, it starts the process for that application (if it's not already running) and instantiates the classes needed for the component.
  8. Tips
    • Query all service with the specified intent:
      Intent intent = new Intent(xxxx);
      PackageManager pm = (PackageManager)getPackageManager();
      List list = pm.queryIntentServices(intent, 0);

      Another: to query all activity with the specified intent:
      Intent intent = new Intent(xxxx);     
      PackageManager pm = (PackageManager)getPackageManager();
      List list = pm.queryIntentActivities(intent, 0);

  9. xx
阅读(1345) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~