Android学习笔记—Service(1、start启动)

来源:互联网 发布:数组大小可以任意改变 编辑:程序博客网 时间:2024/05/01 19:09

1、什么是Service

这里写图片描述

2、服务类型

这里写图片描述

3、本地服务的生命周期

这里写图片描述
两种服务的特点:
这里写图片描述

4、服务启动

4.1、Start启动

首先我们需要一个类继承自Service,并且根据服务的生命周期我们需要复写他的方法代码如下:

package com.example.liujing.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.support.annotation.Nullable;import android.util.Log;/** * Created by liujing on 16/2/1. */public class MyStartService extends Service {    @Override//启动服务是调用此方法    public void onCreate() {        super.onCreate();        Log.d("infoservice","onCreat");    }    @Override//销毁服务是调用此方法    public void onDestroy() {        super.onDestroy();        Log.d("infoservice", "onDestroy");    }    @Override//调用服务方法    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("infoservice", "onStartCommand");        return super.onStartCommand(intent, flags, startId);    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }}

然后我们需要在AndroidManifest对服务进行声明:

<service android:name=".MyStartService"/>

最后回到主线程中启动和停止服务代码如下:
这里写图片描述

0 0
原创粉丝点击