天天看点

Android Service的基本概念

什么是服务

Service

是一个能够在

后台执行

长时间运行的操作应用程序组件,

不提供用户页面

,应用在后台启动一个Service运行,即使用户切换到另外一个应用此Service 也会

继续运行

Service

有以下几个特点:

-

无法与用户直接进行交互

-

必须由用户或其他程序启动

-

优先级介于前台应用和后台应用之间

那么我们什么时候会使用Service呢?例如,打开音乐播放器之后,我们想要打开电子书,而又不希望音乐停止播放,此时就可以使用

Service

Service

具有自己的生命周期。Service服务的生命周期是与Activity生命周期分离的,当Activity被暂停,停止或销毁时,Service组件还可以继续处理其他任务。

服务的类型和创建方式

Android支持服务原因

  1. 允许我们方便的执行后台任务
  2. 实现同一设备上应用之间的垮进程通信。

Android系统支持两种类型服务

  1. 本地服务
  2. 远程服务

创建一个服务,有两种方式:

  1. 启动方式(startService),通过startService()方法启动
  2. 绑定方式(bindService),通过bindService()方法启动

启动方式

Context.startService()

:服务开始无期限运行

Context.stopService()

:被其他组件终止

Context.stopSelf()

:被自己终止

以自启动模式启动的服务需要具备自管理的能力,不需要通过方法调用向外部组件提供数据或功能

绑定方式

Context.bindService()

:绑定后客户端通过ibinder接口和服务通信

Context.unbindService()

:客户端解绑

ServiceConnection

提供数据

一个服务可以绑定多个ServiceConnection同时为不同组件提供服务

被绑定的服务要等待所有服务组件都结束才会被销毁,服务不需要自己终止自己

服务的生命周期

Service

实现中,需要重写一些处理服务生命周期关键特征的回调方法

onCreate()

:放服务被第一次创建时,系统会调用这个方法来执行一次安装过程。

onDestory()

:当服务不再使用或正在销毁时,系统会调用这个方法。

onStartCommand()

:当一个组件通过调用startService()方法请求启动一个服务时,系统会调用其onStartCommand()方法。

onBind()

:当一个组件想通过bindService()方法跟这个服务(如执行RPC)绑定时,系统会调用这个方法

Android Service的基本概念
创建启动类服务

通过startService()方法创建一个启动型的Service,并调用服务的onStartCommand()方法启动服务

启动服务时需要通过intent显示或隐式启动,Intent可以携带一部分数据,在Service的onStartCommand中可以使用其数据

默认启动的服务存在于主线程中,会导致主线程阻塞,故通常采用新线程模式来启动服务

继承Service

继承IntentService

配置Service

在AndroidManifest.xml文件中,配置该Service。有两种配置方法。

显示配置,只需要使用<Service…/>标签声明Service的名称。

<service android:name="Service1">
<!--Service名称-->
</service>
           

隐式配置,除了声明Service名称之外,还需要使用Service配置<intent-filter…/>子标签。通过匹配Action属性,说明该Service可以被哪些Intent启动

<service android:name="Service1">
<intenet-filter>
<!--设置Action属性-->
       <action android:name="android.service"/>
<!--设置Intent类型-->
        <category android:name="android.intenet.category.LAUNCHER">
</intenet-filter>
</service>
           

Service

服务线程通过继承Service类来实现

当一个组件通过调用startService(intent)启动一个服务,系统会调用该服务的onStartCommand()方法

对于每一个启动Service的请求,都会产生一条带有StartId和Intent的Message,并发欧松到MessageQueue中。

Service实现服务可以同时执行多个请求,每个请求是一个全新的线程,会被立即执行,无需等待前一个请求完成

操作步骤

在MainActivity中通过intent启动服务

定义服务类MyService,继承service,完成AndroidManifest注册

重写系统方法

onCreate()

onStartCommand()

onDestory()

根据情况决定是否启动onBind和onUnBind,onRebind等方法

开始

MainActivity.this.startService(intent);//启动 service

Android Service的基本概念

结束

MainActivity.this.stopService(intent);//停止service

Android Service的基本概念

全部代码:

服务类

MyService.java

package com.example.servicelifecycledemo;

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

//服务类
public class MyService extends Service {
    public MyService() {
    }
    final static String TAG="HELLO";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG,"onCreate");
        Toast.makeText(this,"创建后台服务",Toast.LENGTH_LONG).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        Toast.makeText(this,"开始服务",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        Toast.makeText(this,"销毁服务",Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return  null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG,"onRebind");
        super.onRebind(intent);
    }
}

           
Android Service的基本概念

MainActivity.java

package com.example.servicelifecycledemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button1;
    Button button2;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView =findViewById(R.id.textView);
        button1 =findViewById(R.id.btn1);
        button2 =findViewById(R.id.btn2);
        button1.setOnClickListener(new MClick());
        button2.setOnClickListener(new MClick());
        intent=new Intent(this,MyService.class);
    }

    class  MClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {

            switch ((v.getId())){
                case  R.id.btn1:
                    MainActivity.this.startService(intent);//启动 service
                    break;
                case  R.id.btn2:
                    MainActivity.this.stopService(intent);//停止service
                    break;
            }
        }
    }
}

           

activity_main_xml

:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动后台音乐程序"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="@id/textView" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止后台音乐程序"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="@id/btn1" />

</androidx.constraintlayout.widget.ConstraintLayout>
           

谢谢观看 0v0