Service的生命周期 (适用于2.1及以上)

1. 被startService的
无论是否有任何活动绑定到该Service,都在后台运行。onCreate(若需要) -> onStart(int id, Bundle args).  多次startService,则onStart调用多次,但不会创建多个Service实例,只需要一次stop。该Service一直后台运行,直到stopService或者自己的stopSelf()或者资源不足由平台结束。

2. 被bindService的
调用bindService绑定,连接建立服务一直运行。未被startService只是BindService,则onCreate()执行,onStart(int,Bundle)不被调用;这种情况下绑定被解除,平台就可以清除该Service(连接销毁后,会导致解除,解除后就会销毁)。

3. 被启动又被绑定
类似startService的生命周期,onCreate onStart都会调用。

4. 停止服务时
stopService时显式onDestroy()。或不再有绑定(没有启动时)时隐式调用。有bind情况下stopService()不起作用。

以下是一个简单的实现例子,某些部分需要配合logcat观察。
AcMain.java

  1. package jtapp.myservicesamples;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  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. import android.widget.Toast;
  14. public class AcMain extends Activity implements OnClickListener {
  15. private static final String TAG = "AcMain";
  16. private Button btnStart;
  17. private Button btnStop;
  18. private Button btnBind;
  19. private Button btnExit;
  20. /** Called when the activity is first created. */
  21. @Override
  22. public void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.main);
  25. findView();
  26. }
  27. private void findView() {
  28. btnStart = (Button) findViewById(R.id.Start);
  29. btnStop = (Button) findViewById(R.id.Stop);
  30. btnBind = (Button) findViewById(R.id.Bind);
  31. btnExit = (Button) findViewById(R.id.Exit);
  32. btnStart.setOnClickListener(this);
  33. btnStop.setOnClickListener(this);
  34. btnBind.setOnClickListener(this);
  35. btnExit.setOnClickListener(this);
  36. }
  37. @Override
  38. public void onClick(View v) {
  39. Intent intent = new Intent("jtapp.myservicesamples.myservice");
  40. switch(v.getId()) {
  41. case R.id.Start:
  42. startService(intent);
  43. Toast.makeText(this,
  44. "myservice running " + MyService.msec/1000.0 + "s.",
  45. Toast.LENGTH_LONG).show();
  46. break;
  47. case R.id.Stop:
  48. stopService(intent);
  49. Toast.makeText(this,
  50. "myservice running " + MyService.msec/1000.0 + "s.",
  51. Toast.LENGTH_LONG).show();
  52. break;
  53. case R.id.Bind:
  54. bindService(intent, sc, Context.BIND_AUTO_CREATE);
  55. break;
  56. case R.id.Exit:
  57. this.finish();
  58. break;
  59. }
  60. }
  61. private MyService serviceBinder;
  62. private ServiceConnection sc = new ServiceConnection() {
  63. @Override
  64. public void onServiceDisconnected(ComponentName name) {
  65. Log.d(TAG, "in onServiceDisconnected");
  66. serviceBinder = null;
  67. }
  68. @Override
  69. public void onServiceConnected(ComponentName name, IBinder service) {
  70. Log.d(TAG, "in onServiceConnected");
  71. serviceBinder = ((MyService.MyBinder)service).getService();
  72. }
  73. };
  74. @Override
  75. protected void onDestroy() {
  76. //this.unbindService(sc);
  77. //this.stopService(
  78. //                new Intent("jtapp.myservicesamples.myservice"));
  79. super.onDestroy();
  80. }
  81. }

复制代码

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" android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <TextView android:layout_width="fill_parent"
  6. android:layout_height="wrap_content" android:text="@string/hello" />
  7. <Button android:text="Start MyService" android:id="@+id/Start"
  8. android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  9. <Button android:text="Stop MyService" android:id="@+id/Stop"
  10. android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  11. <Button android:text="Bind MyService" android:id="@+id/Bind"
  12. android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  13. <Button android:text="Exit AcMain" android:id="@+id/Exit"
  14. android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  15. </LinearLayout>

复制代码

MyService.java

  1. package jtapp.myservicesamples;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;
  6. import android.util.Log;
  7. public class MyService extends Service {
  8. private static final String TAG = "MyService";
  9. public static long msec = 0;
  10. private boolean bThreadRunning = true;
  11. private final IBinder binder = new MyBinder();
  12. public class MyBinder extends Binder {
  13. MyService getService() {
  14. return MyService.this;
  15. }
  16. }
  17. @Override
  18. public IBinder onBind(Intent intent) {
  19. return binder;
  20. }
  21. @Override
  22. public void onCreate() {
  23. new Thread(new Runnable(){
  24. @Override
  25. public void run() {
  26. while (bThreadRunning) {
  27. try {
  28. Thread.sleep(100);
  29. } catch (InterruptedException e) {
  30. }
  31. Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
  32. }
  33. }
  34. }).start();
  35. }
  36. @Override
  37. public void onDestroy() {
  38. bThreadRunning = false;
  39. super.onDestroy(); // 可以不用
  40. }
  41. }

复制代码

AnndroidManifest.xml

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

复制代码

Android中的Service使用的更多相关文章

  1. Android 中的 Service 全面总结(转载)

    转载地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 感谢作者 Android 中的 Service 全面总结 1.Ser ...

  2. (转载)Android中的Service:Binder,Messenger,AIDL(2)

    前言 前面一篇博文介绍了关于Service的一些基本知识,包括service是什么,怎么创建一个service,创建了一个service之后如何启动它等等.在这一篇博文里有一些需要前一篇铺垫的东西,建 ...

  3. (转载)所有分类 > 开发语言与工具 > 移动开发 > Android开发 Android中的Service:默默的奉献者 (1)

    前言 这段时间在看一些IPC相关的东西,这里面就不可避免的要涉及到service,进程线程这些知识点,而且在研究的过程中我惊觉自己对这些东西的记忆已经开始有些模糊了——这可要不得.于是我就干脆花了点心 ...

  4. Android中的Service小结

    简介 Service适合执行不需要和用户交互,而且长期运行的任务.即使程序被切换回后台,服务仍然可以正常运行.Service并不自动开启线程,默认运行在主线程中. Service中需要重载的函数 on ...

  5. Android 中的 Service 全面总结

    1.Service的种类   按运行地点分类: 类别 区别  优点 缺点   应用 本地服务(Local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另 ...

  6. Android 中的 Service 全面总结 (转)

    原文地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 1.Service的种类   按运行地点分类: 类别 区别  优点 ...

  7. 【转】Android中保持Service的存活

    这几天一直在准备考试,总算有个半天时间可以休息下,写写博客. 如何让Service keep alive是一个很常见的问题. 在APP开发过程中,需要Service持续提供服务的应用场景太多了,比如闹 ...

  8. Android中的service

    1.service简介:service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息 ...

  9. Android中的Service与进程间通信(IPC)详解

    Service 什么是Service 在后台长期运行的没有界面的组件.其他组件可以启动Service让他在后台运行,或者绑定Service与它进行交互,甚至实现进程间通信(IPC).例如,可以让服务在 ...

  10. Android中的Service组件具体解释

    Service与Activity的差别在于:Service一直在后台执行,他没实用户界面,绝不会到前台来. 一,创建和配置Service 开发Service须要两个步骤:1.继承Service子类,2 ...

随机推荐

  1. Java输入输出处理技术1

    1.保存用户输入到文件 从键盘读入一行字符,写到文件output.txt中去. package io; import java.io.*; public class MyFileOutput { pu ...

  2. An easier way to debug windows services

    Have you got tired of attaching the Visual Studio debugger to the service application? I got the sol ...

  3. 第三章 mybatis-generator + mysql/ptsql

    用了mybatis-generator,我就不再想用注解了,这与我之前说的注解与XML并用是矛盾的,知识嘛,本来就是多元化的,今天喜欢这个,明天喜欢那个,哈哈,看了mybatis-generator下 ...

  4. 附4 springboot源码解析-run()

    public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); / ...

  5. string.Format对C#字符串格式化[转]

    string.Format对C#字符串格式化 String.Format 方法的几种定义: String.Format (String, Object) 将指定的 String 中的格式项替换为指定的 ...

  6. 十个WEB开发人员不可不知的HTML5工具

    Initializr 这是一个HTML5模板创建工具,帮助你得到持续的最新的HTML5样板文件. XRAY XRAY目前支持Safari, Firefox和IE浏览器,XRAY使用了CSS3的多个酷炫 ...

  7. 使用swipemenulistview实现列表的左右滑动

    今天从网上找到一个第三方控件swipemenulistview,封装好的一个控件,可以实现列表的左右滑动,模仿qq的列表效果 下载地址为:https://github.com/baoyongzhang ...

  8. hadoop fs:du & count统计hdfs文件(目录下文件)大小的用法

    hadoop fs 更多用法,请参考官网:http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_shell.html 以下是我的使用hadoop fs -du统计文 ...

  9. 在myeclipse中写sql语句的细节问题

    注意类型,varchar 和int  在java中表示为sql语句中的细微区别!! 下面的REGISEAT_NUM为int 类型       custid为varchar类型 String sql1= ...

  10. Mongo命令批量更新某一数组字段的顺序

      db.table.find().forEach(function (doc) {     var oldValue = doc.Column1;     var newValue = [sa[1] ...