Android應用程序開發(fā)技術(shù) 課件 第9章 Service服務_第1頁
Android應用程序開發(fā)技術(shù) 課件 第9章 Service服務_第2頁
Android應用程序開發(fā)技術(shù) 課件 第9章 Service服務_第3頁
Android應用程序開發(fā)技術(shù) 課件 第9章 Service服務_第4頁
Android應用程序開發(fā)技術(shù) 課件 第9章 Service服務_第5頁
已閱讀5頁,還剩24頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

Android應用程序開發(fā)技術(shù)第9章Service服務服務是一個后臺運行的組件,執(zhí)行長時間運行且不需要用戶交互的任務。即使應用被銷毀也依然可以工作。章節(jié)概述9.1

Service簡介

9.2

系統(tǒng)自帶Service9.3

Service實現(xiàn)過程9.4

本章總結(jié)9.5

習題9.6上機目

錄9.1Service簡介9.1.1.Service介紹和作用服務(Service)是Android中實現(xiàn)程序后臺運行的解決方案,也是Android應用四大組件之一。它非常適合去執(zhí)行那些不需要和用戶交互而且還要求長期運行的任務。服務的運行不依賴于任何用戶界面,即使程序被切換到后臺,或者用戶打開了另外一個應用程序,服務仍然能夠保持正常運行。類似于Activity和其它應用組件,開發(fā)人員需要在應用程序配置文件中使用<service></service>標簽聲明全部的service。9.1Service簡介9.1.2.Service的狀態(tài)服務從本質(zhì)上可分為兩種狀態(tài)。1.Started(啟動)當應用程序組件(如Activity)通過startService()方法啟動服務時,服務器處于started狀態(tài)。一旦啟動,服務能在后臺無限期運行(即使啟動它的組件已經(jīng)銷毀)。通常,啟動服務執(zhí)行單個操作并不會向調(diào)用者返回結(jié)果。例如,它可能通過網(wǎng)絡下載或者上傳文件。如果操作完成,服務需要停止自身的運行。2.Bound(綁定)當應用程序組件通過bindService()方法綁定到服務時,服務處于bound狀態(tài)。綁定服務提供客戶端-服務器接口,允許組件與服務交互、發(fā)送請求、獲得結(jié)果,甚至使用進程間通信(IPC)跨進程完成這些操作。僅當其它應用程序與之綁定時,綁定服務才運行。多個組件可以一次綁定到一個服務上,當它們都解除綁定時,服務被銷毀。9.1Service簡介9.1.3.Service生命周期根據(jù)使用方式的不同,Service的生命周期可以分成2條路徑,如圖9-1所示。圖9-1Service的生命周期9.1Service簡介9.1.3.Service生命周期下面詳細分析一下這些回調(diào)方法。onCreate()當Service被創(chuàng)建時回調(diào)。如果Service已經(jīng)在運行,那么不會回調(diào)onCreate()方法。在onCreate()方法中,可以做一些初始化操作。onStartCommand()當有組件調(diào)用startService()方法啟動Service時回調(diào)。在onStartCommand()方法中,可以執(zhí)行后臺任務。由于Service是運行在主線程之中的,所以如果是耗時的任務則需要使用子線程來執(zhí)行任務。在Service完成任務之后,需要有組件調(diào)用stopService()方法來停止Service,或者由Service調(diào)用stopSelf()方法來自行停止。onBind()當有組件調(diào)用bindService()方法與Service綁定時回調(diào)。在onBind()方法中,可以通過返回一個IBinder對象來提供一個接口供客戶端與Service進行通信。onUnbind()方法當客戶端調(diào)用unbindService()方法與Service解除綁定時回調(diào)。onDestroy()當Service停止運行將被銷毀時回調(diào)。當有組件調(diào)用startService()方法來啟動Service時,Service開始運行,直到有組件調(diào)用stopService()方法來停止Service,或者由Service調(diào)用stopSelf()方法來自行停止。當有組件調(diào)用bindService()方法與Service綁定時,Service開始運行,直到所有的客戶端與Service解綁時,Service停止運行。在onDestroy()方法中,應該釋放所有的資源,比如子線程、注冊的監(jiān)聽器和廣播接收器等。9.1Service簡介9.1.1.Service介紹和作用可以用以下代碼來測試Service的生命周期。修改布局文件代碼如下:1.<?xml

version="1.0"

encoding="utf-8"?>

2.<LinearLayout

xmlns:android="/apk/res/android"

3.

android:layout_width="fill_parent"

4.

android:layout_height="fill_parent"

5.

android:orientation="vertical">

6.

7.

<TextView

//設置啟動服務標題格式

8.

android:layout_width="wrap_content"

9.

android:layout_height="wrap_content"

10.

android:text="測試啟動服務"

11.

android:textSize="25sp"/>

13.

<LinearLayout

14.

android:layout_width="match_parent"

15.

android:layout_height="wrap_content">

16.

17.

<Button

//設置啟動服務按鈕

18.

android:id="@+id/btn_start"

19.

android:layout_width="0dp"

20.

android:layout_height="wrap_content"

21.

android:layout_weight="1"

22.

android:onClick="startMyService"

23.

android:text="啟動服務"

/>

24.

25.

<Button

//設置停止服務按鈕

26.

android:id="@+id/btn_stop"

27.

android:layout_width="0dp"

28.

android:layout_height="wrap_content"

29.

android:layout_weight="1"

30.

android:onClick="stopMyService"

31.

android:text="停止服務"

/>

32.

</LinearLayout>

34.

<TextView

//設置測試綁定服務標題格式

35.

android:layout_width="wrap_content"

36.

android:layout_height="wrap_content"

37.

android:text="測試綁定服務"

38.

android:textSize="25sp"

39.

android:layout_marginTop="10dp"/>

40.

41.

<LinearLayout

42.

android:layout_width="match_parent"

43.

android:layout_height="wrap_content">

44.

45.

<Button

//設置綁定服務按鈕格式

46.

android:id="@+id/btn_bind"

47.

android:layout_width="0dp"

48.

android:layout_height="wrap_content"

49.

android:layout_weight="1"

50.

android:onClick="bindMyService"

51.

android:text="綁定服務"

/>

52.

53.

<Button

//設置解綁服務按鈕格式

54.

android:id="@+id/btn_unbind"

55.

android:layout_width="0dp"

56.

android:layout_height="wrap_content"

57.

android:layout_weight="1"

58.

android:onClick="unbindMyService"

59.

android:text="解綁服務"

/>

60.

</LinearLayout>

61.</LinearLayout>

9.1Service簡介9.1.1.Service介紹和作用創(chuàng)建的Service代碼如下:1.public

class

MyService

extends

Service

{

2.

public

MyService(){//創(chuàng)建對象,測試再次運行startService時還會不會再次創(chuàng)建對象

3.

log.i("TAG","調(diào)用了MyService()方法");

4.

}

5.

6.

@Override

7.

public

void

onCreate()

{

8.

super.onCreate();

9.

log.i("TAG","調(diào)用了onCreate()方法");

10.

}

11.

12.

@Override

13.

public

int

onStartCommand(Intent

intent,

int

flags,

int

startId)

{

14.

log.i("TAG","調(diào)用了onStartCommand()方法");

15.

return

super.onStartCommand(intent,

flags,

startId);

16.

}

17.

18.

@Override

19.

public

void

onDestroy()

{

20.

super.onDestroy();

21.

log.i("TAG","調(diào)用了onDestroy()方法");

22.

}

23.

24.

@Override

25.

public

IBinder

onBind(Intent

intent)

{

26.

log.i("TAG","調(diào)用了onbind()方法");

27.

return

new

Binder();

28.

}

29.

30.

@Override

31.

public

boolean

onUnbind(Intent

intent){

32.

log.i("TAG","調(diào)用了onUnbind()方法");

33.

return

true;

34.

}

35.}

9.1

Service簡介

9.2

系統(tǒng)自帶Service9.3

Service實現(xiàn)過程9.4

本章總結(jié)9.5

習題9.6上機目

錄9.2系統(tǒng)自帶Service9.2.1NotificationManager狀態(tài)欄通知必須用到兩個類:

NotificationManager、

Notification。NotificationManager是系統(tǒng)Service,通過getSystemService()方法來獲取,負責發(fā)通知、清除通知等,是狀態(tài)欄通知的管理類。Notification是具體的狀態(tài)欄通知對象,可以設置icon、文字、提示聲音、振動等參數(shù)。創(chuàng)建Notification:通過NotificationManager的notify()方法來啟動Notification。notify()的函數(shù)聲明如下:voidnotify(int,Notification)其中,第一個參數(shù)唯一的標識該Notification,第二個參數(shù)就是Notification對象。更新Notification:調(diào)用Notification的setLatestEventInfo()方法來更新內(nèi)容,然后再調(diào)用NotificationManager的notify()方法即可。setLatestEventInfo()的函數(shù)聲明如下:voidsetLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent);其中,第一個參數(shù)是上下文,第二個參數(shù)是標題,第三個參數(shù)是內(nèi)容,第四個參數(shù)為延時意圖。刪除Notification:通過NotificationManager的cancel(int)方法來清除某個通知。其中參數(shù)就是Notification的唯一標識ID。也可以通過cancelAll()來清除狀態(tài)欄所有的通知。cancel()的函數(shù)聲明如下:voidcancel(intid)其中參數(shù)為移除id。9.2系統(tǒng)自帶Service9.2.2DownloadManagerDownloadManager是一種處理長時間運行的HTTP下載的系統(tǒng)服務。客戶端可以請求將Uri下載到特定目標文件。DownloadManager將在后臺進行下載,負責HTTP交互并在發(fā)生故障或連接更改和系統(tǒng)重新啟動后重試下載。使用DownloadManager時,必須申請Manifest.permission.INTERNET權(quán)限。獲取這個類的實例的方式有:Context.getSystemService(Class),參數(shù)為DownloadManager.class。Context.getSystemService(String),參數(shù)為Context.DOWNLOAD_SERVICE。9.2系統(tǒng)自帶Service9.2.2DownloadManager使用DownloadManager時,必須申請Manifest.permission.INTERNET權(quán)限。獲取這個類的實例的方式有:Context.getSystemService(Class),參數(shù)為DownloadManager.class。Context.getSystemService(String),參數(shù)為Context.DOWNLOAD_SERVICE。主要的接口和類:1.內(nèi)部類DownloadManager.Query,這個類可以用于過濾DownloadManager的請求。2.內(nèi)部類DownloadManager.Request,這個類包含請求一個新下載連接的必要信息。3.公共方法enqueue,在隊列中插入一個新的下載。當連接正常并DownloadManager準備執(zhí)行這個請求時,開始自動下載。返回結(jié)果是系統(tǒng)提供的唯一下載ID,這個ID可以用于與下載相關(guān)的回調(diào)。4.公共方法query(),用于查詢下載信息。5.公共方法remove(),用于刪除下載。如果正在下載則取消下載并刪除下載文件和記錄。9.1

Service簡介

9.2

系統(tǒng)自帶Service9.3

Service實現(xiàn)過程9.4

本章總結(jié)9.5

習題9.6上機目

錄9.3Service實現(xiàn)過程9.3.1創(chuàng)建Service在應用程序包名上右擊,在彈出的目錄中依次選擇NewServiceService選項來創(chuàng)建Service類,在彈出的對話框中寫入Service名稱,點擊Finish按鈕創(chuàng)建出一個Service。通過這種方式創(chuàng)建好的Service會在AndroidManifest.xml文件中進行注冊,若手動創(chuàng)建Service類,則需要注冊如下代碼:1.<service

2.

android:name=".MyService"

3.

android:enabled="ture"

4.

android:exported="ture"

5.</service>

9.3Service實現(xiàn)過程9.3.2啟動和綁定Service(已將服務替換為Service)1.啟動Service開發(fā)人員可以通過Activity或者其它應用程序組件傳遞Intent對象到startService()方法中啟動Service。系統(tǒng)將調(diào)用onstartCommand()方法將Intent傳遞給Service。例如在Activity內(nèi)寫入: Intentintent=newintent(this,MyService.class);

startService(intent);9.3Service實現(xiàn)過程9.3.2啟動和綁定Service(已將服務替換為Service)1.啟動Service由于Service沒有提供綁定,所以startService()方法發(fā)送的Intent是應用程序和Service之間唯一的通訊模式。因此當需要Service返回結(jié)果時,啟動該Service的客戶端廣播創(chuàng)建PendingIntent并通過啟動Service的Intent發(fā)送它,Service就可以使用廣播發(fā)送結(jié)果。每一次Service請求都將調(diào)用一次onstartCommand()方法,還可以接收Intent信息,因此開發(fā)人員大多情況下將Service的主要運行代碼重寫在onstartCommand()方法中,而不是onCreate()方法中。1. @Override

2.

public

int

onStartCommand(Intent

intent,

int

flags,

int

startId)

{

3.

log.i("TAG","調(diào)用了onStartCommand()方法");

4.

return

super.onStartCommand(intent,

flags,

startId);

5.}

9.3Service實現(xiàn)過程9.3.2啟動和綁定Service(已將服務替換為Service)2.綁定Service應用程序組件(客戶端)能調(diào)用bindService()方法綁定到Service。Android系統(tǒng)接下來調(diào)用Service的onBind()方法,它返回IBinder來與Service通信。為了接收IBinder,客戶端必須建立ServiceConnection實例然后將其傳遞給bindService()方法。ServiceConnection包含系統(tǒng)調(diào)用發(fā)送IBinder的回調(diào)方法。從客戶端綁定Service需要完成以下操作:1)實現(xiàn)ServiceConnection(),這需要重寫onServiceConnection()和onServiceDisconnection()兩個回調(diào)方法;2)調(diào)用bindService()方法,傳遞ServiceConnection實現(xiàn);3)當系統(tǒng)調(diào)用onServiceConnection()回調(diào)方法時,就可以將接口定義的方法調(diào)用到Service;4)調(diào)用unbindService()方法解除綁定。當客戶端銷毀時,會將其從Service上解除綁定。但是當與Service完成交互或者Activity暫停時,需解除綁定以便系統(tǒng)能及時停止不用的Service。9.3Service實現(xiàn)過程9.3.3使用Service實現(xiàn)音樂播放器示例【例9-1】創(chuàng)建Android項目,使用Service實現(xiàn)音樂播放器。修改res/layout包中的main.xml文件,定義應用程序的背景圖片和框架,代碼如下:1.<?xml

version="1.0"

encoding="utf-8"?>

2.<LinearLayout

xmlns:android="/apk/res/android"

3.

android:layout_width="match_parent"

4.

android:layout_height="match_parent"

5.

android:background="@mipmap/bg"

6.

android:gravity="center"

7.

android:orientation="vertical">

8.

9.

<ImageView

//設置音樂轉(zhuǎn)盤圖片格式

10.

android:id="@+id/disk"

11.

android:layout_width="240dp"

12.

android:layout_height="240dp"

13.

android:layout_gravity="center_horizontal"

14.

android:layout_margin="15dp"

15.

android:src="@drawable/disk"

/>

16.

17.

<RelativeLayout

//圖片與操作的分割線

18.

android:layout_width="match_parent"

19.

android:layout_height="wrap_content"

20.

android:paddingLeft="8dp"

21.

android:paddingRight="8dp">

22.

</RelativeLayout>

23.

24.

<LinearLayout

25.

android:layout_width="match_parent"

26.

android:layout_height="wrap_content"

27.

android:orientation="horizontal">

28.

29.

<Button

//播放按鈕格式

30.

android:id="@+id/btn_play"

31.

android:layout_width="0dp"

32.

android:layout_height="40dp"

33.

android:layout_weight="1"

34.

android:text="播放音樂"

/>

35.

36.

<Button

//暫停按鈕格式

37.

android:id="@+id/btn_pause"

38.

android:layout_width="0dp"

39.

android:layout_height="40dp"

40.

android:layout_weight="1"

41.

android:text="暫停播放"

/>

42.

43.

<Button

//繼續(xù)按鈕格式

44.

android:id="@+id/btn_continue"

45.

android:layout_width="0dp"

46.

android:layout_height="40dp"

47.

android:layout_weight="1"

48.

android:text="繼續(xù)播放"

/>

49.

50.

<Button

//退出按鈕格式

51.

android:id="@+id/btn_exit"

52.

android:layout_width="0dp"

53.

android:layout_height="40dp"

54.

android:layout_weight="1"

55.

android:text="退出"

/>

56.

</LinearLayout>

57.</LinearLayout>

9.3Service實現(xiàn)過程9.3.3使用Service實現(xiàn)音樂播放器示例創(chuàng)建一個PlayerService類繼承Service類重寫服務的生命周期中需要的方法,代碼如下:1.import

android.app.Service;

2.import

android.content.Intent;

3.import

android.media.MediaPlayer;

4.import

android.os.Binder;

5.import

android.os.IBinder;

6.

7.public

class

PlayerService

extends

Service

{//創(chuàng)建PlayerService類

8.

private

MediaPlayer

player;//多媒體對象

9.

private

MusicControl

control;//音樂控制器

10.

public

PlayerService()

{

11.

}

12.

13.

@Override

14.

public

IBinder

onBind(Intent

intent)

{

15.

return

new

MusicControl();//綁定服務,將控制類實例化

16.

}

17.

18.

@Override

19.

public

void

onCreate()

{//設置服務開始時需要創(chuàng)建的對象

20.

super.onCreate();

21.

player

=

new

MediaPlayer();

22.

control

=

new

MusicControl();

23.

}

25.

@Override

26.

public

int

onStartCommand(Intent

intent,

int

flags,

int

startId)

{

27.

String

action

=

intent.getStringExtra("action");

28.

if("play".equals(action)){

29.

control.play();//播放音樂

30.

}else

if("pause".equals(action)){

31.

control.pause();//暫停音樂

32.

}else

if("continue".equals(action)){

33.

ceed();//繼續(xù)音樂

34.

}

35.

return

super.onStartCommand(intent,

flags,

startId);

36.

}

37.

38.

@Override

39.

public

void

onDestroy()

{

40.

super.onDestroy();

41.

}

43.

class

MusicControl

extends

Binder{

44.

//播放音樂

45.

public

void

play(){

46.

player.reset();

47.

player

=

MediaPlayer.create(getApplicationContext(),R.raw.skyhigh);

48.

player.start();

49.

}

50.

//暫停音樂

51.

public

void

pause(){

52.

player.pause();

53.

}

54.

//繼續(xù)音樂

55.

public

void

proceed(){

56.

player.start();

57.

}

58.

//停止音樂

59.

public

void

stop(){

60.

player.stop();

61.

player.release();

62.

}

63.

}

64.}

9.3Service實現(xiàn)過程9.3.3使用Service實現(xiàn)音樂播放器示例在MainActivity類中完成客戶端需要的內(nèi)容,代碼如下:1.import

androidx.appcompat.app.AppCompatActivity;

2.import

android.animation.ObjectAnimator;

3.import

android.content.ComponentName;

4.import

android.content.Intent;

5.import

android.content.ServiceConnection;

6.import

android.os.Bundle;

7.import

android.os.IBinder;

8.import

android.view.View;

9.import

android.view.animation.LinearInterpolator;

10.import

android.widget.Button;

11.import

android.widget.ImageView;

12.13.public

class

MainActivity

extends

AppCompatActivity

implements

View.OnClickListener{

14.

private

Button

btn_play,btn_pause,btn_continue,btn_exit;//四個功能控件

15.

private

PlayerService.MusicControl

control;//定義一個音樂控制器

16.

private

ObjectAnimator

animator;//定義轉(zhuǎn)盤的控制器

17.

private

ImageView

disk;//定義轉(zhuǎn)盤

18.

19.

private

ServiceConnection

conn

=new

ServiceConnection()

{//建立服務的鏈接

20.

@Override

21.

public

void

onServiceConnected(ComponentName

name,

IBinder

service)

{

22.

control

=

(PlayerService.MusicControl)service;//接收IBinder類

23.

}

24.

25.

@Override

26.

public

void

onServiceDisconnected(ComponentName

name)

{

28.

}

29.

};

30.

@Override

31.

protected

void

onCreate(Bundle

savedInstanceState)

{

32.

super.onCreate(savedInstanceState);

33.

setContentView(R.layout.activity_main);

34.

35.

init();//activity開始時設置的一些初始化

36.

}

37.

38.public

void

init(){

39.

//設置點擊事件

40.

btn_play

=

(Button)

findViewById(R.id.btn_play);

41.

btn_pause

=

(Button)findViewById(R.id.btn_pause);

42.

btn_continue

=

(Button)findViewById(R.id.btn_continue);

43.

btn_exit

=

(Button)findViewById(R.id.btn_exit);

44.

45.

btn_play.setOnClickListener(this);

46.

btn_pause.setOnClickListener(this);

47.

btn_continue.setOnClickListener(this);

48.

btn_exit.setOnClickListener(this);

49.

//設置轉(zhuǎn)盤

50.

disk

=

findViewById(R.id.disk);

51.

animator

=

ObjectAnimator.ofFloat(disk,"rotation",0,360.0F);//disk

旋轉(zhuǎn)

從零度到三百六十度

52.

animator.setDuration(10000);//設置動畫時長,設置10秒一圈

53.

animator.setInterpolator(new

LinearInterpolator());//線性勻速

54.

animator.setRepeatCount(-1);//設置圈數(shù),-1表示一直旋轉(zhuǎn)

55.

56.

}

57.

58.

9.3Service實現(xiàn)過程9.3.3使用Service實現(xiàn)音樂播放器示例在MainActivity類中完成客戶端需要的內(nèi)容,代碼如下:59.

@Override

60.

public

void

onClick(View

v)

{//設置點擊功能

61.

Intent

intent

=

new

Intent(this,PlayerService.class);

62.

if(btn_play==v){//播放

63.

intent.putExtra("action","play");

64.

startService(intent);

65.

animator.start();//轉(zhuǎn)盤轉(zhuǎn)動

66.

67.

}

else

if(btn_pause==v){

68.

intent.putExtra("action","pause");

69.

startService(intent);

70.

animator.pause();//轉(zhuǎn)盤暫停

71.

}

else

if(btn_continue==v){

72.

intent.putExtra("action","continue");

73.

startService(intent);

74.

animator.resume();//轉(zhuǎn)盤繼續(xù)

75.

}

else

if(btn_exit==v){

76.

stopService(intent);

77.

finish();

78.

}

79.

}

80.}

9.3Service實現(xiàn)過程9.3.3使用Service實現(xiàn)音樂播放器示例若是手動創(chuàng)建Service類則需要在AndroidManifest.xml文件中進行注冊,其代碼如下:1.<?xml

version="1.0"

encoding="utf-8"?>

2.<manifest

xmlns:android="/apk/res/android"

3.

package="com.example.playerservice">

4.

5.

<application

6.

android:allowBackup="true"

7

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論