Skip to content
Julius Yu edited this page Jan 9, 2014 · 10 revisions

什么是Service?

  • 通常意义的Service
  • 定义

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.


为什么用Service?


应用场景

  • 举例

了解Service

  • 创建方式

    • startService
    • bindService

  • 生命周期

    • onCreate
    • onStartCommand

      START_STICKY START_NOT_STICKY START_REDELIVER_INTENT

    • onDestroy
    • onUnbind
    • onRebind
    • onBind

  • 重要方法

    • stopSelf (final)
      • stopSelf(int) 可以让Service处理完已经开始的Intent再停止
    • stopService
    • startForeground
    • stopForeground

  • Notes

    • service 可以是私有的
    • gracefully handle restarts by the system

代码

private void acceptInterview() {

        Message message = JsonUtils.readModel(this, "sample.json",
                              "accept_message_sample", Message.class);
        //启动service
        startService(new Intent(this, MessageService.class) 
                        .putExtra("message", message));
    }

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

        if (intent.getExtras() != null) {
            Message message = (Message) intent.getExtras().get("message");
            long id = ServiceFactory.getInstance()
                          .getMessageService().addMessage(message);
        }
        Ln.e("msg service onStartCommand");

        //停止Service
        stopSelf();

        return START_NOT_STICKY;
    }

有什么问题吗?


和它们之间的关系

  • Activity
  • Thread

IntentService

  • 什么要用它,除了它还是其它方法吗?

  • 和它们之间的关系

    • Handler
    • AsynTask