Android应用程序开发技术 课件 第9章 Service服务_第1页
Android应用程序开发技术 课件 第9章 Service服务_第2页
Android应用程序开发技术 课件 第9章 Service服务_第3页
Android应用程序开发技术 课件 第9章 Service服务_第4页
Android应用程序开发技术 课件 第9章 Service服务_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Android应用程序开发技术第9章Service服务服务是一个后台运行的组件,执行长时间运行且不需要用户交互的任务。即使应用被销毁也依然可以工作。章节概述9.1

Service简介

9.2

系统自带Service9.3

Service实现过程9.4

本章总结9.5

习题9.6上机目

录9.1Service简介9.1.1.Service介绍和作用服务(Service)是Android中实现程序后台运行的解决方案,也是Android应用四大组件之一。它非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。服务的运行不依赖于任何用户界面,即使程序被切换到后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。类似于Activity和其它应用组件,开发人员需要在应用程序配置文件中使用<service></service>标签声明全部的service。9.1Service简介9.1.2.Service的状态服务从本质上可分为两种状态。1.Started(启动)当应用程序组件(如Activity)通过startService()方法启动服务时,服务器处于started状态。一旦启动,服务能在后台无限期运行(即使启动它的组件已经销毁)。通常,启动服务执行单个操作并不会向调用者返回结果。例如,它可能通过网络下载或者上传文件。如果操作完成,服务需要停止自身的运行。2.Bound(绑定)当应用程序组件通过bindService()方法绑定到服务时,服务处于bound状态。绑定服务提供客户端-服务器接口,允许组件与服务交互、发送请求、获得结果,甚至使用进程间通信(IPC)跨进程完成这些操作。仅当其它应用程序与之绑定时,绑定服务才运行。多个组件可以一次绑定到一个服务上,当它们都解除绑定时,服务被销毁。9.1Service简介9.1.3.Service生命周期根据使用方式的不同,Service的生命周期可以分成2条路径,如图9-1所示。图9-1Service的生命周期9.1Service简介9.1.3.Service生命周期下面详细分析一下这些回调方法。onCreate()当Service被创建时回调。如果Service已经在运行,那么不会回调onCreate()方法。在onCreate()方法中,可以做一些初始化操作。onStartCommand()当有组件调用startService()方法启动Service时回调。在onStartCommand()方法中,可以执行后台任务。由于Service是运行在主线程之中的,所以如果是耗时的任务则需要使用子线程来执行任务。在Service完成任务之后,需要有组件调用stopService()方法来停止Service,或者由Service调用stopSelf()方法来自行停止。onBind()当有组件调用bindService()方法与Service绑定时回调。在onBind()方法中,可以通过返回一个IBinder对象来提供一个接口供客户端与Service进行通信。onUnbind()方法当客户端调用unbindService()方法与Service解除绑定时回调。onDestroy()当Service停止运行将被销毁时回调。当有组件调用startService()方法来启动Service时,Service开始运行,直到有组件调用stopService()方法来停止Service,或者由Service调用stopSelf()方法来自行停止。当有组件调用bindService()方法与Service绑定时,Service开始运行,直到所有的客户端与Service解绑时,Service停止运行。在onDestroy()方法中,应该释放所有的资源,比如子线程、注册的监听器和广播接收器等。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介绍和作用创建的Service代码如下:1.public

class

MyService

extends

Service

{

2.

public

MyService(){//创建对象,测试再次运行startService时还会不会再次创建对象

3.

log.i("TAG","调用了MyService()方法");

4.

}

5.

6.

@Override

7.

public

void

onCreate()

{

8.

super.onCreate();

9.

log.i("TAG","调用了onCreate()方法");

10.

}

11.

12.

@Override

13.

public

int

onStartCommand(Intent

intent,

int

flags,

int

startId)

{

14.

log.i("TAG","调用了onStartCommand()方法");

15.

return

super.onStartCommand(intent,

flags,

startId);

16.

}

17.

18.

@Override

19.

public

void

onDestroy()

{

20.

super.onDestroy();

21.

log.i("TAG","调用了onDestroy()方法");

22.

}

23.

24.

@Override

25.

public

IBinder

onBind(Intent

intent)

{

26.

log.i("TAG","调用了onbind()方法");

27.

return

new

Binder();

28.

}

29.

30.

@Override

31.

public

boolean

onUnbind(Intent

intent){

32.

log.i("TAG","调用了onUnbind()方法");

33.

return

true;

34.

}

35.}

9.1

Service简介

9.2

系统自带Service9.3

Service实现过程9.4

本章总结9.5

习题9.6上机目

录9.2系统自带Service9.2.1NotificationManager状态栏通知必须用到两个类:

NotificationManager、

Notification。NotificationManager是系统Service,通过getSystemService()方法来获取,负责发通知、清除通知等,是状态栏通知的管理类。Notification是具体的状态栏通知对象,可以设置icon、文字、提示声音、振动等参数。创建Notification:通过NotificationManager的notify()方法来启动Notification。notify()的函数声明如下:voidnotify(int,Notification)其中,第一个参数唯一的标识该Notification,第二个参数就是Notification对象。更新Notification:调用Notification的setLatestEventInfo()方法来更新内容,然后再调用NotificationManager的notify()方法即可。setLatestEventInfo()的函数声明如下:voidsetLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent);其中,第一个参数是上下文,第二个参数是标题,第三个参数是内容,第四个参数为延时意图。删除Notification:通过NotificationManager的cancel(int)方法来清除某个通知。其中参数就是Notification的唯一标识ID。也可以通过cancelAll()来清除状态栏所有的通知。cancel()的函数声明如下:voidcancel(intid)其中参数为移除id。9.2系统自带Service9.2.2DownloadManagerDownloadManager是一种处理长时间运行的HTTP下载的系统服务。客户端可以请求将Uri下载到特定目标文件。DownloadManager将在后台进行下载,负责HTTP交互并在发生故障或连接更改和系统重新启动后重试下载。使用DownloadManager时,必须申请Manifest.permission.INTERNET权限。获取这个类的实例的方式有:Context.getSystemService(Class),参数为DownloadManager.class。Context.getSystemService(String),参数为Context.DOWNLOAD_SERVICE。9.2系统自带Service9.2.2DownloadManager使用DownloadManager时,必须申请Manifest.permission.INTERNET权限。获取这个类的实例的方式有:Context.getSystemService(Class),参数为DownloadManager.class。Context.getSystemService(String),参数为Context.DOWNLOAD_SERVICE。主要的接口和类:1.内部类DownloadManager.Query,这个类可以用于过滤DownloadManager的请求。2.内部类DownloadManager.Request,这个类包含请求一个新下载连接的必要信息。3.公共方法enqueue,在队列中插入一个新的下载。当连接正常并DownloadManager准备执行这个请求时,开始自动下载。返回结果是系统提供的唯一下载ID,这个ID可以用于与下载相关的回调。4.公共方法query(),用于查询下载信息。5.公共方法remove(),用于删除下载。如果正在下载则取消下载并删除下载文件和记录。9.1

Service简介

9.2

系统自带Service9.3

Service实现过程9.4

本章总结9.5

习题9.6上机目

录9.3Service实现过程9.3.1创建Service在应用程序包名上右击,在弹出的目录中依次选择NewServiceService选项来创建Service类,在弹出的对话框中写入Service名称,点击Finish按钮创建出一个Service。通过这种方式创建好的Service会在AndroidManifest.xml文件中进行注册,若手动创建Service类,则需要注册如下代码:1.<service

2.

android:name=".MyService"

3.

android:enabled="ture"

4.

android:exported="ture"

5.</service>

9.3Service实现过程9.3.2启动和绑定Service(已将服务替换为Service)1.启动Service开发人员可以通过Activity或者其它应用程序组件传递Intent对象到startService()方法中启动Service。系统将调用onstartCommand()方法将Intent传递给Service。例如在Activity内写入: Intentintent=newintent(this,MyService.class);

startService(intent);9.3Service实现过程9.3.2启动和绑定Service(已将服务替换为Service)1.启动Service由于Service没有提供绑定,所以startService()方法发送的Intent是应用程序和Service之间唯一的通讯模式。因此当需要Service返回结果时,启动该Service的客户端广播创建PendingIntent并通过启动Service的Intent发送它,Service就可以使用广播发送结果。每一次Service请求都将调用一次onstartCommand()方法,还可以接收Intent信息,因此开发人员大多情况下将Service的主要运行代码重写在onstartCommand()方法中,而不是onCreate()方法中。1. @Override

2.

public

int

onStartCommand(Intent

intent,

int

flags,

int

startId)

{

3.

log.i("TAG","调用了onStartCommand()方法");

4.

return

super.onStartCommand(intent,

flags,

startId);

5.}

9.3Service实现过程9.3.2启动和绑定Service(已将服务替换为Service)2.绑定Service应用程序组件(客户端)能调用bindService()方法绑定到Service。Android系统接下来调用Service的onBind()方法,它返回IBinder来与Service通信。为了接收IBinder,客户端必须建立ServiceConnection实例然后将其传递给bindService()方法。ServiceConnection包含系统调用发送IBinder的回调方法。从客户端绑定Service需要完成以下操作:1)实现ServiceConnection(),这需要重写onServiceConnection()和onServiceDisconnection()两个回调方法;2)调用bindService()方法,传递ServiceConnection实现;3)当系统调用onServiceConnection()回调方法时,就可以将接口定义的方法调用到Service;4)调用unbindService()方法解除绑定。当客户端销毁时,会将其从Service上解除绑定。但是当与Service完成交互或者Activity暂停时,需解除绑定以便系统能及时停止不用的Service。9.3Service实现过程9.3.3使用Service实现音乐播放器示例【例9-1】创建Android项目,使用Service实现音乐播放器。修改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

//设置音乐转盘图片格式

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

//继续按钮格式

44.

android:id="@+id/btn_continue"

45.

android:layout_width="0dp"

46.

android:layout_height="40dp"

47.

android:layout_weight="1"

48.

android:text="继续播放"

/>

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实现过程9.3.3使用Service实现音乐播放器示例创建一个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

{//创建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()

{//设置服务开始时需要创建的对象

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();//继续音乐

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.

//继续音乐

55.

public

void

proceed(){

56.

player.start();

57.

}

58.

//停止音乐

59.

public

void

stop(){

60.

player.stop();

61.

player.release();

62.

}

63.

}

64.}

9.3Service实现过程9.3.3使用Service实现音乐播放器示例在MainActivity类中完成客户端需要的内容,代码如下: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;//定义转盘的控制器

17.

private

ImageView

disk;//定义转盘

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.

//设置转盘

50.

disk

=

findViewById(R.id.disk);

51.

animator

=

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

旋转

从零度到三百六十度

52.

animator.setDuration(10000);//设置动画时长,设置10秒一圈

53.

animator.setInterpolator(new

LinearInterpolator());//线性匀速

54.

animator.setRepeatCount(-1);//设置圈数,-1表示一直旋转

55.

56.

}

57.

58.

9.3Service实现过程9.3.3使用Service实现音乐播放器示例在MainActivity类中完成客户端需要的内容,代码如下: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();//转盘转动

66.

67.

}

else

if(btn_pause==v){

68.

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

69.

startService(intent);

70.

animator.pause();//转盘暂停

71.

}

else

if(btn_continue==v){

72.

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

73.

startService(intent);

74.

animator.resume();//转盘继续

75.

}

else

if(btn_exit==v){

76.

stopService(intent);

77.

finish();

78.

}

79.

}

80.}

9.3Service实现过程9.3.3使用Service实现音乐播放器示例若是手动创建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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论