这篇文章我是看到一些前辈的知识整理的,在此声明下。

1.Context.startService()方式启动:

①Context.startService()方式的生命周期: 

启动时,startService –> onCreate() –> onStart();停止时,stopService –> onDestroy()。

如果调用者直接退出而没有停止Service,则Service 会一直在后台运行 Context.startService()方法启动服务,在服务未被创建时,

系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用

startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用startService()方法启动的服务,

只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

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

①Context.bindService()方式的生命周期:

 绑定时,bindService -> onCreate() –> onBind();调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()。

Context.bindService()方式启动 Service的方法:绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);

第一个:Intent对象;第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()

来判断连接成功或者是断开连接;第三个:如何创建Service,一般指定绑定的时候自动创建。

附代码    

package com.dada.test;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import android.widget.Button;import com.dada.test.BindService.MyBinder;public class TestActivity extends Activity {private boolean flag;private static final String TAG = "TestActivity";    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                super.onCreate(savedInstanceState);         setContentView(R.layout.main);          Button btnStart = (Button) findViewById(R.id.btnStart);          Button btnStop = (Button) findViewById(R.id.btnStop);                  btnStart.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {             //启动service 方式2            bindService();            }         });                 btnStop.setOnClickListener(new View.OnClickListener() {                      @Override             public void onClick(View v) {  //停止service 方式2            unBindService();            }         });     }        //启动service 方式2    //    private void bindService(){        Intent intent = new Intent(TestActivity.this,BindService.class);        Log.i(TAG, "bindService()");        bindService(intent, conn, Context.BIND_AUTO_CREATE);    }        private void unBindService(){    Log.i(TAG, "unBindService() start....");        if(flag == true){        Log.i(TAG, "unBindService() flag");            unbindService(conn);            flag = false;        }    }    private ServiceConnection conn = new ServiceConnection() {                @Override        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub        Log.i(TAG, "onServiceDisconnected()");        }                @Override        public void onServiceConnected(ComponentName name, IBinder service) {            // TODO Auto-generated method stub        Log.i(TAG, "onServiceConnected()");            MyBinder binder = (MyBinder)service;            BindService bindService = binder.getService1();            bindService.MyMethod();            flag = true;        }    };}

package com.dada.test;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class BindService extends Service {    private static final String TAG = "BindService";    private MyBinder myBinder = new MyBinder();    public void MyMethod(){        Log.i(TAG, "BindService-->MyMethod()");    }        @Override    public IBinder onBind(Intent intent) {    Log.i(TAG, "BindService-->onBind()");        return myBinder;    }        public class MyBinder extends Binder{                public BindService getService1(){            return BindService.this;        }    }      @Overridepublic void onCreate() {Log.i(TAG, "BindService-->onCreate()");super.onCreate();}@Overridepublic void onStart(Intent intent, int startId) {Log.i(TAG, "BindService-->onStart()");super.onStart(intent, startId);}@Overridepublic void onDestroy() {Log.i(TAG, "BindService-->onDestroy()");super.onDestroy();}@Overridepublic boolean onUnbind(Intent intent) {Log.i(TAG, "BindService-->onUnbind()");return super.onUnbind(intent);}}

运行日志

点击启动


点击停止


没有打出onServiceDisconnected的日志的原因:

注:SDK上是这么说的:This is called when the connection with the service has been 
unexpectedly disconnected -- that is, its process crashed. Because it is running in our same 
process, we should never see this happen.

所以说,只有在service因异常而断开连接的时候,这个方法才会用到

其他

由于Service 的onStart()方法只有在startService()启动Service的情况下才调用,故使用onStart()的时候要注意这点。

与 Service 通信并且让它持续运行

      如果我们想保持和 Service 的通信,又不想让 Service 随着 Activity 退出而退出呢?你可以先 startService() 然后再 bindService() 。

当你不需要绑定的时候就执行 unbindService() 方法,执行这个方法只会触发 Service 的 onUnbind() 而不会把这个 Service 销毁。

这样就可以既保持和 Service 的通信,也不会随着 Activity 销毁而销毁了。


*************************************************************

再说下bindService于绑定者之间的调用关系:

由于Android 中的Service使用了onBind 的方法去绑定服务,返回一个Ibinder对象进行操作(Ibinder对象是onServiceConnected的参数,

一般在这里获得Ibinder),而我们要获取具体的Service方法的内容的时候,我们需要Ibinder对象返回具体的Service对象才能操作,

所以说具体的Service对象必须首先实现Binder对象,这个样子的话我们才能利用bindService的方法对Service进行绑定,

获取Binder对象之后获取具体的Service对象,然后才获取Service中的方法等等。所以我们需要注意的是bindService的

方式去绑定服务获取的必定是实现了Binder的对象,所以这是我们必须使用Binder的方式去获取Service的方式而不是

直接使用Service的类,这个是Android内部实现所约束的。

方法过程如下:

Intent intent = new Intent(MainActivity.this,BindService.class)->新建了BindService对象->新建了MyBinder对象

->bindService(intent, conn, Context.BIND_AUTO_CREATE);->onBind()函数  -----传递MyBinder对象------->onServiceConnected()

 --> 通过传递的Binder对象获取刚刚和Binder对象对应的BindService 对象  -->调用Service中定义的方法。

    这个其中必须通过Binder对象,因为是通过Binder对象来传递的,通过Binder对象获取Service对象,然后获取所需的服务,

所以Service必须实现Binder,以便传递和使用。


好了,说到这基本也把Service的基本用法搞定了。


更多相关文章

  1. 打开Android(安卓)C文件中的LOG
  2. Android的Window底层原理
  3. android软键盘不覆盖屏幕方法
  4. Android游戏引擎《Rokon》:主要类和方法的介绍文档
  5. Android实战技巧:用Pull方法解析XML文件
  6. Android(安卓)listView+CheckBox的实现
  7. 使用android中的AIDL让Service与Activity通信
  8. Android(安卓)Studio下Svn忽略文件配置的几种方法
  9. Android(安卓)Arrayadapter 获得数据方法

随机推荐

  1. Android 系统(194)---Android实践 -- 设置
  2. Android 列表选择框 Spinner详解及实例
  3. android camera研究
  4. android UI设计,android ui开发,android
  5. Android中集成QQ登陆和QQ空间分享
  6. Android(安卓)权限中文说明
  7. android socket通信(下)
  8. android layout属性简介
  9. Android中几种数据结构使用
  10. android 隐藏键盘 ----- 断点记录