Service是Android中的四大组件之一,所以在Android开发过程中起到非常重要的作用。下面我们来看一下官方对Service的定义。

AServiceis an application component thatcan perform long-running operations in the background and does not provide auser interface. Another application component can start a service and it willcontinue to run in the background even if the user switches to anotherapplication. Additionally, a component can bind to a service to interact withit and even perform interprocess communication (IPC). For example, a servicemight handle network transactions, play music, perform file I/O, or interactwith a content provider, all from the background.

对应的中文就是:Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

【博客专栏:http://blog.csdn.net/column/details/alearning.html

Service有两种状态,“启动”和“绑定”。

在上一部分我们介绍了Activity生命周期,在介绍Service的过程中,我们同样需要介绍Service的生命周期的概念。

以下是Service的生命周期图:

Service服务:

是一段长生命周期,没有用户界面的程序,可以用来开发监控类程序。较好的例子是:正在从播放列表中播放歌曲的媒体播放器。在一个媒体播放器的应用中,应该会有很多歌Activity,让使用者可以选择歌曲并播放歌曲。然而,音乐重放这个功能并没有对应的Activity,因为使用者当然会认为在导航到其他屏幕时音乐应该是持续播放的。在这个例子中,媒体播放器这个Activity会使用Context.startService()来启动一个service,从而可以再后台保持音乐的播放。同时,系统也将保持这个service一直执行,知道这个service运行结束。另外,我们还可以通过使用Context.bindService()方法,连接到一个service上(如果这个service还没有运行将启动它)。当连接到一个service之后,我们还可以service提供的接口与它进行通讯。拿媒体播放器这个例子来说,我们还可以进行暂停、重播等操作。

Service的使用步骤

1、继承Service

2AndroidManifast.xml配置清单文件中<application>节点里对服务进行配置

<span style="font-size:18px;"><!-- 注册Service服务 -->        <service            android:name="cn.mahaochen.app.alearning.chapter5.TestService"            android:enabled="true" >        </service></span>

服务不能自己运行,需要通过Contex.startService()Contex.bindService()启动服务。

通过startService()方法启动的服务于调用者没有关系,即使调用者关闭了,服务仍然运行想停止服务要调用Context.stopService(),此时系统会调用onDestory(),使用此方法启动时,服务首次启动系统先调用服务的onCreate()-->onStart()

如果服务已经启动再次调用只会触发onStart()方法。使用bindService()启动的服务与调用者绑定,只要调用者关闭服务就终止,使用此方法启动时,服务首次启动系统先调用服务的。onCreate()-->onBind(),如果服务已经启动再次调用不会再触发这2个方法,调用者退出时系统会调用服务的onUnbind()-->onDestory()

想主动解除绑定可使用Contex.unbindService(),系统依次调用onUnbind()-->onDestory()

测试代码:TestService

import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class TestService extends Service {// 定义Tag标签private static final String TAG = "TestService";private MyBinder mBinder = new MyBinder();  @Overridepublic IBinder onBind(Intent intent) {Log.e(TAG, "TestService start IBinder .");  return mBinder;  //return null;}@Overridepublic void onCreate() {Log.e(TAG, "TestService start onCreate .");super.onCreate();}@Overridepublic void onStart(Intent intent, int startId) {Log.e(TAG, "TestService start onStart .");super.onStart(intent, startId);}@Overridepublic void onDestroy() {Log.e(TAG, "TestService start onDestroy .");super.onDestroy();}@Overridepublic boolean onUnbind(Intent intent) {Log.e(TAG, "TestService start onUnbind .");return super.onUnbind(intent);}public class MyBinder extends Binder {public TestService getService() {return TestService.this;}}}

ServiceActivity

import android.app.Activity;import android.content.ComponentName;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceActivity extends Activity {private TestService testService;private Button stopServiceButton; // 停止Service按钮private Button bindServiceButton; // 绑定Service按钮private Button unBindServiceButton; // 解除绑定Service按钮// 这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到private ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {testService = ((TestService.MyBinder) service).getService();}@Overridepublic void onServiceDisconnected(ComponentName name) {}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 设置主布局文件XMLsetContentView(R.layout.activity_chapter5_service);initViews();}// 初始化视图private void initViews() {stopServiceButton = (Button) findViewById(R.id.stopService_button);bindServiceButton = (Button) findViewById(R.id.bindService_button);unBindServiceButton = (Button) findViewById(R.id.unBindService_button);SrvActOnClickListener clickListener = new SrvActOnClickListener();stopServiceButton.setOnClickListener(clickListener);bindServiceButton.setOnClickListener(clickListener);unBindServiceButton.setOnClickListener(clickListener);}// 内部类,由于本类只有ServiceActivity自己使用,所以采用内部类,然而内部的使用场景不局限于此private class SrvActOnClickListener implements OnClickListener {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.stopService_button:Toast.makeText(ServiceActivity.this, "stopService",Toast.LENGTH_SHORT).show();break;case R.id.bindService_button:Toast.makeText(ServiceActivity.this, "bindService",Toast.LENGTH_SHORT).show();break;case R.id.unBindService_button:Toast.makeText(ServiceActivity.this, "unBindService",Toast.LENGTH_SHORT).show();break;default:break;}}}}

参考资料

1http://blog.csdn.net/ryantang03/article/details/7770939

2http://blog.csdn.net/android_tutor/article/details/5789203

更多相关文章

  1. Android(安卓)应用安装流程初探
  2. android画笔错位问题的解决
  3. 解决Content的startActivity方法报错
  4. Android(安卓)aspectJ Aop
  5. Android通过反射实现强制停止应用程序的方法
  6. MediaPlayer+Stagefright架构(音频)图解
  7. 【android】解决Viewpager设置高度为wrap_content无效的方法
  8. Android(安卓)JNI入门第三篇——jni头文件分析

随机推荐

  1. “12306”的架构到底有多牛逼?
  2. go语言使用revel框架实现用户注册教程(附
  3. golang能否替代php
  4. go语言中channel的详细介绍
  5. .go是什么文件
  6. getch()的功能是什么
  7. go语言基础
  8. C语言字符串输出函数puts()的作用是什么
  9. c语言绝对值怎么打
  10. go语言适合做什么?