天天看點

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