Android四大基本组件之 Service

一.Service的简介

1.Service介绍和作用

Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了。

2.Service生命周期

Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。

二.Service的启动方式

Service的有两种启动方式:Context.startService()和Context.bindService(),这两种方式对Service生命周期的影响是不同的。

1.Context.startService()方式启动

①Context.startService()方式的生命周期: 启动时,startService –> onCreate() –> onStart() 停止时,stopService –> onDestroy()

如果调用者直接退出而没有停止Service,则Service 会一直在后台运行

Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

②Context.startService()方式启动 Service的方法:

下面是具体例子:

MainActivity.java

  1. package com.android.service.activity;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. public class MainActivity extends Activity
  9. {
  10. private Button startBtn;
  11. private Button stopBtn;
  12. @Override
  13. public void onCreate(Bundle savedInstanceState)
  14. {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. startBtn = (Button) findViewById(R.id.startBtn);
  18. stopBtn = (Button) findViewById(R.id.stopBtn);
  19. //添加监听器
  20. startBtn.setOnClickListener(listener);
  21. stopBtn.setOnClickListener(listener);
  22. }
  23. //启动监听器
  24. private OnClickListener listener=new OnClickListener()
  25. {
  26. @Override
  27. public void onClick(View v)
  28. {
  29. Intent intent=new Intent(MainActivity.this, ServiceDemo.class);
  30. switch (v.getId())
  31. {
  32. case R.id.startBtn:
  33. startService(intent);
  34. break;
  35. case R.id.stopBtn:
  36. stopService(intent);
  37. break;
  38. default:
  39. break;
  40. }
  41. }
  42. };
  43. }

ServiceDemo.java

  1. package com.android.service.activity;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. import android.util.Log;
  6. public class ServiceDemo extends Service
  7. {
  8. private static final String TAG="Test";
  9. @Override
  10. //Service时被调用
  11. public void onCreate()
  12. {
  13. Log.i(TAG, "Service onCreate--->");
  14. super.onCreate();
  15. }
  16. @Override
  17. //当调用者使用startService()方法启动Service时,该方法被调用
  18. public void onStart(Intent intent, int startId)
  19. {
  20. Log.i(TAG, "Service onStart--->");
  21. super.onStart(intent, startId);
  22. }
  23. @Override
  24. //当Service不在使用时调用
  25. public void onDestroy()
  26. {
  27. Log.i(TAG, "Service onDestroy--->");
  28. super.onDestroy();
  29. }
  30. @Override
  31. //当使用startService()方法启动Service时,方法体内只需写return null
  32. public IBinder onBind(Intent intent)
  33. {
  34. return null;
  35. }
  36. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <Button
  8. android:id="@+id/startBtn"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:text="启动 Service"
  12. />
  13. <Button
  14. android:id="@+id/stopBtn"
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:text="停止 Service"
  18. />
  19. </LinearLayout>

在AndroidManifest.xml文件中添加16~21行的声明

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.android.service.activity"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <uses-sdk android:minSdkVersion="10" />
  7. <application android:icon="@drawable/icon" android:label="@string/app_name">
  8. <activity android:name=".MainActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <action android:name="android.intent.action.MAIN" />
  12. <category android:name="android.intent.category.LAUNCHER" />
  13. </intent-filter>
  14. </activity>
  15. <service android:name=".ServiceDemo" >
  16. <intent-filter>
  17. <action android:name="android.intent.action.MAIN" />
  18. <category android:name="android.intent.category.LAUNCHER" />
  19. </intent-filter>
  20. </service>
  21. </application>
  22. </manifest>

效果图:

当点击按钮时,先后执行了Service中onCreate()->onStart()这两个方法,LogCat显示如下:

当点击 按钮时,Service则执行了onDestroy()方法,LogCat显示如下:

当点击按钮,进入Settings(设置)->Applications(应用)->Running Services(正在运行的服务)看一下我们新启动了的服务,效果图如下:

2.Context.bindService()方式启动:

①Context.bindService()方式的生命周期: 绑定时,bindService -> onCreate() –> onBind()

调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()

用Context.bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onBind()方法。这个时候调用者和服务绑定在一起,调用者退出了,系统就会先调用服务的onUnbind()方法,接着调用onDestroy()方法。如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致多次创建服务及绑定(也就是说onCreate()和onBind()方法并不会被多次调用)。如果调用者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。

②Context.bindService()方式启动 Service的方法:

绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);

第一个:Intent对象

第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()来判断连接成功或者是断开连接

第三个:如何创建Service,一般指定绑定的时候自动创建

下面是具体的例子:

MainActivity.java

  1. package com.android.bindservice.activity;
  2. import android.app.Activity;
  3. import android.app.Service;
  4. import android.content.ComponentName;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;
  13. public class MainActivity extends Activity {
  14. // 声明Button
  15. private Button startBtn,stopBtn,bindBtn,unbindBtn;
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. // 设置当前布局视图
  20. setContentView(R.layout.main);
  21. // 实例化Button
  22. startBtn = (Button)findViewById(R.id.startBtn1);
  23. stopBtn = (Button)findViewById(R.id.stopBtn2);
  24. bindBtn = (Button)findViewById(R.id.bindBtn3);
  25. unbindBtn = (Button)findViewById(R.id.unbindBtn4);
  26. // 添加监听器
  27. startBtn.setOnClickListener(startListener);
  28. stopBtn.setOnClickListener(stopListener);
  29. bindBtn.setOnClickListener(bindListener);
  30. unbindBtn.setOnClickListener(unBindListener);
  31. }
  32. // 启动Service监听器
  33. private OnClickListener startListener = new OnClickListener() {
  34. @Override
  35. public void onClick(View v) {
  36. // 创建Intent
  37. Intent intent = new Intent();
  38. // 设置Class属性
  39. intent.setClass(MainActivity.this, BindService.class);
  40. // 启动该Service
  41. startService(intent);
  42. }
  43. };
  44. // 停止Service监听器
  45. private OnClickListener stopListener = new OnClickListener() {
  46. @Override
  47. public void onClick(View v) {
  48. // 创建Intent
  49. Intent intent = new Intent();
  50. // 设置Class属性
  51. intent.setClass(MainActivity.this, BindService.class);
  52. // 启动该Service
  53. stopService(intent);
  54. }
  55. };
  56. // 连接对象
  57. private ServiceConnection conn = new ServiceConnection() {
  58. @Override
  59. public void onServiceConnected(ComponentName name, IBinder service) {
  60. Log.i("Service", "连接成功!");
  61. }
  62. @Override
  63. public void onServiceDisconnected(ComponentName name) {
  64. Log.i("Service", "断开连接!");
  65. }
  66. };
  67. // 綁定Service监听器
  68. private OnClickListener bindListener = new OnClickListener() {
  69. @Override
  70. public void onClick(View v) {
  71. // 创建Intent
  72. Intent intent = new Intent();
  73. // 设置Class属性
  74. intent.setClass(MainActivity.this, BindService.class);
  75. // 绑定Service
  76. bindService(intent, conn, Service.BIND_AUTO_CREATE);
  77. }
  78. };
  79. // 解除绑定Service监听器
  80. private OnClickListener unBindListener = new OnClickListener() {
  81. @Override
  82. public void onClick(View v) {
  83. // 创建Intent
  84. Intent intent = new Intent();
  85. // 设置Class属性
  86. intent.setClass(MainActivity.this, BindService.class);
  87. // 解除绑定Service
  88. unbindService(conn);
  89. }
  90. };
  91. }

BindService.java

  1. package com.android.bindservice.activity;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. import android.util.Log;
  6. public class BindService extends Service{
  7. private static final String TAG="Test";
  8. //返回null
  9. public IBinder onBind(Intent intent) {
  10. Log.i(TAG, "Service onBind--->");
  11. return null;
  12. }
  13. // Service创建时调用
  14. public void onCreate() {
  15. Log.i(TAG, "Service onCreate--->");
  16. }
  17. // 当客户端调用startService()方法启动Service时,该方法被调用
  18. public void onStart(Intent intent, int startId) {
  19. Log.i(TAG, "Service onStart--->");
  20. }
  21. // 当Service不再使用时调用
  22. public void onDestroy() {
  23. Log.i(TAG, "Service onDestroy--->");
  24. }
  25. // 当解除绑定时调用
  26. public boolean onUnbind(Intent intent) {
  27. Log.i(TAG, "Service onUnbind--->");
  28. return super.onUnbind(intent);
  29. }
  30. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <Button
  8. android:text="启动Service"
  9. android:id="@+id/startBtn1"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. />
  13. <Button
  14. android:text="停止Service"
  15. android:id="@+id/stopBtn2"
  16. android:layout_width="match_parent"
  17. android:layout_height="wrap_content"
  18. />
  19. <Button
  20. android:text="绑定Service"
  21. android:id="@+id/bindBtn3"
  22. android:layout_width="match_parent"
  23. android:layout_height="wrap_content"
  24. />
  25. <Button
  26. android:text="解除绑定"
  27. android:id="@+id/unbindBtn4"
  28. android:layout_width="match_parent"
  29. android:layout_height="wrap_content"
  30. />
  31. </LinearLayout>

在AndroidManifest.xml文件中添加16~21行的声明

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.android.bindservice.activity"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <uses-sdk android:minSdkVersion="10" />
  7. <application android:icon="@drawable/icon" android:label="@string/app_name">
  8. <activity android:name=".MainActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <action android:name="android.intent.action.MAIN" />
  12. <category android:name="android.intent.category.LAUNCHER" />
  13. </intent-filter>
  14. </activity>
  15. <service android:name=".BindService" >
  16. <intent-filter>
  17. <action android:name="android.intent.action.MAIN" />
  18. <category android:name="android.intent.category.LAUNCHER" />
  19. </intent-filter>
  20. </service>
  21. </application>
  22. </manifest>

效果图:

当点击按钮时,先后执行了Service中onCreate()->onStart()这两个方法,LogCat显示如下:

当点击按钮,则Service执行了onUnbind()方法,LogCat显示如下:

当点击按钮,则Service执行了onUnbind()方法,LogCat显示如下:

时间: 2024-08-27 19:52:12

Android四大基本组件之 Service的相关文章

android四大基础组件--Service生命周期详解

android四大基础组件--ServiceService 生命周期详解 1.Service的生命周期: I> 在非绑定Service情况下,只有oncreate(),onStartCommand(),onDestory()方法情况下:  操作方法对应生命周期一: a.[执行startService(Intent)] 执行生命周期方法:oncreate()--->onStartCommand(): b.[执行stopService(Intent)] 执行生命周期方法:onDestory();

Android四大基本组件(1)之Activity与BroadcastReceive广播接收器

Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器. 一.Activity (1)应用程序中,一个Activity通常就是一个单独的屏幕,它上面可以显示一些控件也可以监听并处理用户的事件做出响应. (2)Activity之间通过Intent进行通信.在Intent 的描述结构中,有两个最重要的部分:动作和动作对应的数据. (3)典型的动作类型有:M AIN(activity的门户).VIE

Android四大基本组件介绍与生命周期介绍。

Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器. 一:了解四大基本组件 Activity : 应用程序中,一个Activity通常就是一个单独的屏幕,它上面可以显示一些控件也可以监听并处理用户的事件做出响应. Activity之间通过Intent进行通信.在Intent 的描述结构中,有两个最重要的部分:动作和动作对应的数据. 典型的动作类型有:M AIN(activity的门户).V

关于Android四大基本组件介绍与生命周期(转)

Android四大基本组件介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器. 一:了解四大基本组件 Activity : 应用程序中,一个Activity通常就是一个单独的屏幕,它上面可以显示一些控件也可以监听并处理用户的事件做出响应. Activity之间通过Intent进行通信.在Intent 的描述结构中,有两个最重要的部分:动作和动作对应的数据. 典型的动作类型有

Android四大基本组件介绍与生命周期

主要参考: 1.http://blog.csdn.net/android_tutor/article/details/5772285 2.http://www.cnblogs.com/bravestarrhu/archive/2012/05/02/2479461.html Android四大基本组件介绍与生命周期,布布扣,bubuko.com

Android四大基本组件(3)之四大组件总结

关于四大基本组件的一个总结: 1> 4大组件的注册 4大基本组件都需要注册才能使用,每个Activity.service.Content Provider内容提供者都需要在AndroidManifest文件中进行配置AndroidManifest文件中未进行声明的activity.服务以及内容提供者将不为系统所见,从而也就不可用,而BroadcastReceive广播接收者的注册分静态注册(在AndroidManifest文件中进行配置)和通过代码动态创建并以调用Context.register

Android四大基本组件之 BroadcastReceiver介绍

本文主要介绍BroadcastReceiver的概念.使用.生命周期.安全性.分类.特殊的BroadcastReceiver(本地.粘性.有序.粘性有序广播). 示例代码见BroadcastReceiverDemo,示例APK见:TrineaAndroidDemo.apk. 1.概念介绍及两种注册方式的区别 BroadcastReceiver作为Android四大组件之一,不像Activity,没有可显示的界面.BroadcastReceiver包括两个概念,广播发送者和广播接收者(Receiv

Android四大基本组件-Service详解

一.官方文档 Class Overview A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service c

Android四大基本组件(2)之Service 服务与Content Provider内容提供者

一.Service 服务: 一个Service 是一段长生命周期的,没有用户界面的程序,可以用来开发如监控类程序. 比较好的一个例子就是一个正在从播放列表中播放歌曲的媒体播放器.在一个媒体播放器的应用中,应该会有多个activity,让使用者可以选择歌曲并播放歌曲.然而,音乐重放这个功能并没有对应的activity,因为使用者当然会认为在导航到其它屏幕时音乐应该还在播放的.在这个例子中,媒体播放器这个activity 会使用Context.startService()来启动一个service,从