服务的生命周期

新建一个项目

创建包service

创建类

package ml.yompc.servicedemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * @email yom535@outlook.com
 * @author: 有民(yom535)
 * 学号:1703010141
 * @date: 2019/11/5
 * @time: 16:02
 */
public class FristService extends Service {
    private final String TAG=FristService.class.getName();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //服务创建时
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"onCreate....");
    }
    //服务结束时
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy....");
    }
    //服务启动时
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"onStartCommand....");
        return super.onStartCommand(intent, flags, startId);
    }
}

四大组件都要注册

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ml.yompc.servicedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".service.FristService">

        </service>
    </application>

</manifest>

主要增加了

<service android:name=".service.FristService">

        </service>

启动服务

新建两个Button

package ml.yompc.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import ml.yompc.servicedemo.service.FristService;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //开启服务
    public void startService(View view) {
        Intent intent=new Intent();
        intent.setClass(this,FristService.class);
        startService(intent);
    }
    //停止服务
    public void stopService(View view) {
        Intent intent=new Intent();
        intent.setClass(this,FristService.class);
        stopService(intent);
    }
}