美文网首页
Some points 4. - Service

Some points 4. - Service

作者: Jinjins1129 | 来源:发表于2017-02-27 00:01 被阅读0次

    在Some points 1中对四大组件做了概览,这里详细记录一下官方文档上对Service做出的说明。

    service运行在所在进程的主线程的,除了指定进程或线程,默认情况下既不会创建自己的线程也不会运行在另外的进程。因此如果 service 中执行了CPU敏感型的操作或其他阻塞线程的操作例如访问网络等,需要在 service 内另起线程来执行,否则会 ANR。

    Service的类型

    • Scheduled - 在Android 5.0中新增的API JobSchedule中,service是被计划执行的,可以指定执行所需的网络环境和时间节点。
    • Started - Context.startService(),一旦启动服务可在后台无限期运行,即使启动服务的组件被销毁也不受影响。例:网络下载、上传文件。
    • Bound - Context.bindService(),绑定服务提供了一个客户端-服务器接口,允许组件与服务进行交互、发送请求、获取结果,甚至是利用进程间通信(IPC)跨进程执行这些操作。多个组件可以同时绑定该服务,但全部取消绑定后,该服务即被销毁。
      一个 service 可以同时是 started 和 bound 的。

    Create a service

    因为 service 是一个 Android 组件,因此也需要像 activity 一样在 manifest 中的 application 结点中声明。export=false属性可以防止其他应用启动本service。

    Create a started service

    当调用 Context.startService() ,就创建了started service,通过传递intent来指明服务的名称和携带数据,Service类中的onStartCommand()被回调,在这个方法中可以接收传递过来的intent。有两个类供继承来实现service:Service 和 IntentService。前者是所有service的基类,可以自行实现各种回调方法;后者是Service的一个子类,默认另启了一个工作线程来执行请求,如果不需要处理多重请求的话这是最佳的选择,只需实现onHandleIntent()来接收intent然后执行操作。

    • extends IntentService
      IntentService做了以下事情:

      • 创建了一个默认的工作线程来执行所有传递给onStartCommand()的intents,独立于应用的主线程。
      • 创建了一个工作队列,一次只向onHandleIntent()传递一个intent,无需担心多线程问题。
      • 在所有的服务请求都处理完毕后自动停止服务,无需再手动调用stopSelf()
      • 提供了onBind()返回null的默认实现。
      • 提供了onStartCommand()的默认实现,向工作队列发送intent,然后传至onHandleIntent()
    • extends Service
      而当有多线程需要,选择直接继承Service来实现的话,则需要手动实现一系列方法。Services文档中有一段代码示例演示了如何继承Service来实现,同时在service内开启了另外的线程来执行操作。

    public class HelloService extends Service {
      private Looper mServiceLooper;
      private ServiceHandler mServiceHandler;
    
      // Handler that receives messages from the thread
      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.
              try {
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
                  // Restore interrupt status.
                  Thread.currentThread().interrupt();
              }
              stopSelf(msg.arg1);
          }
      }
    
      @Override
      public void onCreate() {
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
    
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
      }
    
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    
          Message msg = mServiceHandler.obtainMessage();
          msg.arg1 = startId;
          mServiceHandler.sendMessage(msg);
    
          // If we get killed, after returning from here, restart
          return START_STICKY;
      }
    
      @Override
      public IBinder onBind(Intent intent) {
          return null;
      }
    
      @Override
      public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
      }
    }
    

    值得注意的是在onStartCommand()中需要返回一个 int ,这个返回值描述了当系统杀死 service 后系统如何继续这个 service 。有以下3种值:

    • START_NOT_STICKY : 除非有新的intent传递过来,否则不重新创建service。
    • START_STICKY : 重新创建service,除非新传递过来 intent 否则以空 intent 调用onStartCommand() ,适用场景是Media player,service被系统杀死后立即重新创建,但是不执行任何命令,等待着用户的操作。
    • START_REDELIVER_INTENT: 立即重新生成service并且传入最后传递的intent,适用场景是需要立即恢复的操作,例如文件下载。

    当 service 没有被 bound 的话,startService()是唯一的调用组件与 service 通信的入口,如果想返回结果用以交互,可以创建PendingIntent来发送广播,传递给service。

    继承Service时需要stopService()来停止服务,当有多个请求连续回调onStartCommand()时,可以调用stopService(startId)来关闭,当此方法内的参数 startId 与 onStartCommand() 内的startId不一致时,不会关闭 service。

    Create a bound service

    当调用 Context.bindService() ,就创建了bound service。四大组件中只有Activity、Service 、Content Provider可以绑定服务,Broadcast receiver不可以绑定。应用场景为:应用中的组件想要通过service进行通信,以及向其他应用公开一些本应用的功能(IPC)。

    要实现bound service,需要实现Service.onBind()方法来返回一个IBinder对象用以实现client与service的交互。调用 Context.bindService(Intent service,ServiceConnection,int flags)时需要提供一个 ServiceConnection 来监听 client 与 service 的连接, bindService() 是异步的,此方法会立即返回,且返回值是一个空值,但连接建立后,系统会回调 ServiceConnection 的 onServiceConnected() 方法,并且传回那个IBinder对象。多个client可以同时绑定同一个service,但是系统只会在第一个client绑定时回调service的onBind()方法,后续的其他client绑定时直接返回相同的IBinder对象而不再回调onBind()方法。

    当最后一个 client 与 service 解绑时,service 会被系统销毁,除非同时也调用了Context.startService()使得服务同时也是一个started service,这时需要显式地调用stopService()stopService()来停止服务。

    通常有3种方法来实现 IBinder:
    (1) Extending the Binder class : 当服务为应用内的私有服务,或不涉及到应用内的跨进程通信时,使用这种方式来实现。client 接到在 service中定义的Binder对象来持有service的入口进而调用service内的方法。
    (2) Using a Messenger : 当需要跨进程时,使用此方式。在service内new Messenger(Handler),Messenger.getBinder()可获得IBinder对象
    用以进程间通信,使用 Handler & Message 实现service对于client发送过来的数据的处理,同时 client 也可以定义自己的Messenger,来处理service回传过来的数据。
    这是实现IPC最简单的方式,因为 Messenger 将所有的请求排队到了单个线程中,因此无需设计service为线程安全的。
    (3) Using AIDL : 全称为 Android Interface Definition Language ,将对象分解为原语,系统可以理解这些对象并在进程间编排它们以执行IPC。Messenger就是基于AIDL作为底层结构实现的,如果想要服务实现多线程需求可以AIDL实现,但一般来说这种需求很少见。

    Context.bindService(Intent service,ServiceConnection,int flags)时需使用显式intent 来绑定服务,因为隐式intent 无法保证什么样的服务会被响应,存在安全隐患。在Android 5.0+使用隐式intent 来 bindService 会抛出异常。

    Service 生命周期

    LifeCircle : started service & bound service
    Code about how to extend Binder :
    public class LocalService extends Service {
        // Binder given to clients
        private final IBinder mBinder = new LocalBinder();
        // Random number generator
        private final Random mGenerator = new Random();
    
        /**
         * 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.
         */
        public class LocalBinder extends Binder {
            LocalService getService() {
                // Return this instance of LocalService so clients can call public methods
                return LocalService.this;
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }
    
        /** method for clients */
        public int getRandomNumber() {
          return mGenerator.nextInt(100);
        }
    }
    
    public class BindingActivity extends Activity {
        LocalService mService;
        boolean mBound = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            // Bind to LocalService
            Intent intent = new Intent(this, LocalService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
        }
    
        /** Called when a button is clicked (the button in the layout file attaches to
          * this method with the android:onClick attribute) */
        public void onButtonClick(View v) {
            if (mBound) {
                // 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();
            }
        }
    
        /** Defines callbacks for service binding, passed to bindService() */
        private ServiceConnection mConnection = new ServiceConnection() {
    
            @Override
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                // We've bound to LocalService, cast the IBinder and get LocalService instance
                LocalBinder binder = (LocalBinder) service;
                mService = binder.getService();
                mBound = true;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName arg0) {
                mBound = false;
            }
        };
    }
    

    Code about how to use a Messenger :

    public class MessengerService extends Service {
        /** Command to the service to display a message */
        static final int MSG_SAY_HELLO = 1;
    
        /**
         * Handler of incoming messages from clients.
         */
        class IncomingHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_SAY_HELLO:
                        Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        }
    
        /**
         * Target we publish for clients to send messages to IncomingHandler.
         */
        final Messenger mMessenger = new Messenger(new IncomingHandler());
    
        /**
         * When binding to the service, we return an interface to our messenger
         * for sending messages to the service.
         */
        @Override
        public IBinder onBind(Intent intent) {
            Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
            return mMessenger.getBinder();
        }
    }
    
    public class ActivityMessenger extends Activity {
        /** Messenger for communicating with the service. */
        Messenger mService = null;
    
        /** Flag indicating whether we have called bind on the service. */
        boolean mBound;
    
        /**
         * Class for interacting with the main interface of the service.
         */
        private ServiceConnection mConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                // This is called when the connection with the service has been
                // established, giving us the object we can use to
                // interact with the service.  We are communicating with the
                // service using a Messenger, so here we get a client-side
                // representation of that from the raw IBinder object.
                mService = new Messenger(service);
                mBound = true;
            }
    
            public void onServiceDisconnected(ComponentName className) {
                // This is called when the connection with the service has been
                // unexpectedly disconnected -- that is, its process crashed.
                mService = null;
                mBound = false;
            }
        };
    
        public void sayHello(View v) {
            if (!mBound) return;
            // Create and send a message to the service, using a supported 'what' value
            Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            // Bind to the service
            bindService(new Intent(this, MessengerService.class), mConnection,
                Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Some points 4. - Service

          本文链接:https://www.haomeiwen.com/subject/lygnwttx.html