Service是Android的四大组件之一,以下是我结合Android Doc和网上资料的学习总结,有不准确的地方请高手指出,互相学习嘛。。。

这篇文章讲的非常好 http://www.2cto.com/kf/201404/296058.html

1.Service是什么
Service是Android的四大组件之一,即Android系统的服务(不是一个线程,是主程序的一部分),与Activity不同,它是不能与用户交互的,不能自己启动的,需要调用Context.startService()来启动,运行后台,如果我们退出应用时,Service进程并没有结束,它仍然在后台行。比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我们就听不到歌了,所以这时候就得用到Service了。


2.Service生命周期
onCreate() 创建Service
onStart(Intent intent, int startId) 启动Service
onDestroy() 销毁Service
onBind() 返回一个IBinder接口对象给Service

3.启动和停止Service
①启动:startService(Intent intent)来启动Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onStart()方法。
②停止:stopService(Intent intent)来停止Service,这时Service会调用自身的onDestory()方法。


4.绑定Service
调用bindService(Intent service, ServiceConnection conn, int flags)来绑定一个Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onBind()方法返回客户端一个IBinder接口对象
。(注意:如果返回null,ServiceConnection对象的方法将不会被调用)
参数①service:Intent对象 。
参数②conn:ServiceConnection对象,实现其onServiceConnected()和onServiceDisconnected()在连接成功和断开连接时处理。
参数③flags:Service创建的方式,一般用Service.BIND_AUTO_CREATE表示绑定时自动创建。

5.示例代码,下载android_service.rar

MainActivity用来操作Service

view plain copy to clipboard print ?
  1. publicclassMainActivityextendsActivity{
  2. privateButtonstartBtn;
  3. privateButtonstopBtn;
  4. privateButtonbindBtn;
  5. privateButtonunBindBtn;
  6. privatestaticfinalStringTAG="MainActivity";
  7. privateLocalServicemyService;
  8. @Override
  9. publicvoidonCreate(BundlesavedInstanceState){
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.main);
  12. startBtn=(Button)findViewById(R.id.start);
  13. stopBtn=(Button)findViewById(R.id.stop);
  14. bindBtn=(Button)findViewById(R.id.bind);
  15. unBindBtn=(Button)findViewById(R.id.unbind);
  16. startBtn.setOnClickListener(newMyOnClickListener());
  17. stopBtn.setOnClickListener(newMyOnClickListener());
  18. bindBtn.setOnClickListener(newMyOnClickListener());
  19. unBindBtn.setOnClickListener(newMyOnClickListener());
  20. }
  21. classMyOnClickListenerimplementsOnClickListener{
  22. @Override
  23. publicvoidonClick(Viewv){
  24. Intentintent=newIntent();
  25. intent.setClass(MainActivity.this,LocalService.class);
  26. switch(v.getId()){
  27. caseR.id.start:
  28. //启动Service
  29. startService(intent);
  30. break;
  31. caseR.id.stop:
  32. //停止Service
  33. stopService(intent);
  34. break;
  35. caseR.id.bind:
  36. //绑定Service
  37. bindService(intent,conn,Service.BIND_AUTO_CREATE);
  38. break;
  39. caseR.id.unbind:
  40. //解除Service
  41. unbindService(conn);
  42. break;
  43. }
  44. }
  45. }
  46. privateServiceConnectionconn=newServiceConnection(){
  47. @Override
  48. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  49. Log.e(TAG,"连接成功");
  50. //当Service连接建立成功后,提供给客户端与Service交互的对象(根据AndroidDoc翻译的,不知道准确否。。。。)
  51. myService=((LocalService.LocalBinder)service).getService();
  52. }
  53. @Override
  54. publicvoidonServiceDisconnected(ComponentNamename){
  55. Log.e(TAG,"断开连接");
  56. myService=null;
  57. }
  58. };
  59. }

Service实体类

view plain copy to clipboard print ?
  1. publicclassLocalServiceextendsService{
  2. privatestaticfinalStringTAG="MyService";
  3. privatefinalIBindermyBinder=newLocalBinder();
  4. @Override
  5. publicIBinderonBind(Intentintent){
  6. Log.e(TAG,"onBind()");
  7. Toast.makeText(this,"onBind()",Toast.LENGTH_SHORT).show();
  8. returnmyBinder;
  9. }
  10. //调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法
  11. @Override
  12. publicvoidonCreate(){
  13. Log.e(TAG,"onCreate()");
  14. Toast.makeText(this,"onCreate()",Toast.LENGTH_SHORT).show();
  15. }
  16. //调用startService方法启动Service时调用该方法
  17. @Override
  18. publicvoidonStart(Intentintent,intstartId){
  19. Log.e(TAG,"onStart()");
  20. Toast.makeText(this,"onStart()",Toast.LENGTH_SHORT).show();
  21. }
  22. //Service创建并启动后在调用stopService方法或unbindService方法时调用该方法
  23. @Override
  24. publicvoidonDestroy(){
  25. Log.e(TAG,"onDestroy()");
  26. Toast.makeText(this,"onDestroy()",Toast.LENGTH_SHORT).show();
  27. }
  28. //提供给客户端访问
  29. publicclassLocalBinderextendsBinder{
  30. LocalServicegetService(){
  31. returnLocalService.this;
  32. }
  33. }
  34. }

需要在AndroidManifest.xml中注册建立的Service

view plain copy to clipboard print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.snail"android:versionCode="1"android:versionName="1.0">
  4. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
  5. <activityandroid:name=".MainActivity"android:label="@string/app_name">
  6. <intent-filter>
  7. <actionandroid:name="android.intent.action.MAIN"/>
  8. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  9. </intent-filter>
  10. </activity>
  11. <!--注册Service-->
  12. <serviceandroid:name="LocalService">
  13. <intent-filter>
  14. <actionandroid:name="com.snail.LocalService"/>
  15. </intent-filter>
  16. </service>
  17. </application>
  18. </manifest>

布局文件main.xml

view plain copy to clipboard print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <Buttonandroid:id="@+id/start"android:layout_width="wrap_content"
  6. android:layout_height="wrap_content"android:text="启动Service"/>
  7. <Buttonandroid:id="@+id/stop"android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"android:text="停止Service"/>
  9. <Buttonandroid:id="@+id/bind"android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"android:text="绑定Service"/>
  11. <Buttonandroid:id="@+id/unbind"android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"android:text="解除Service"/>
  13. </LinearLayout>

程序运行截图:

Android中Service组件详解 .(转载)_第1张图片

依次点击四个按钮后的打印日志:

Android中Service组件详解 .(转载)_第2张图片

更多相关文章

  1. android中实现view的更新UI有两组方法的问题
  2. Could not find SDK_Root\tools\adb.exe 的解决方法
  3. Android高手进阶教程(八)-------Android中两种设置全屏的方法!!!
  4. Android Studio导入.so库文件方法
  5. (转)Android 应用程序退出后不在运行列表中显示的方法
  6. android 数据双向绑定学习笔记
  7. Android Gallery控件使用方法详解

随机推荐

  1. Android物联网开发从入门到实战
  2. Umeng推送消息的坑,Android Service的andr
  3. 你到底懂Android吗?了解多少?
  4. Android仿人人客户端(v5.7.1)——项目框架
  5. Android(安卓)使用Intent传递数据的实现
  6. 基于NanoHttpd的Android视频服务器开发
  7. Android 获取android密钥哈希码(keytool -
  8. 苹果悄悄进入企业级市场,iOS起飞,Android折
  9. repo 和 git 管理源代码
  10. Android带进度条的下载图片示例(AsyncTask