Service简单总结

来源:互联网 发布:一念之差网络大电影 编辑:程序博客网 时间:2024/06/05 17:41


两种运行模式:直接启动  or  绑定,对应的生命周期如上图所示。
大概总结:
模式一:调用方无法与Service有效通信。startService()激活,stopService()关闭。
模式二:调用方可以与Service进行通信。多个调用方可以绑定同一个Service,只有所有调用方都解绑定了,Service才销毁。
               bindService( Intent, ServiceConnection, 连接方式);//绑定时,与ServiceConnection连接对象相关联
                   会触发Service生命周期中的onBind()方法,该方法返回一个Binder对象
                    ——> 会触发上面ServiceConnection的 onServiceConnection(Binder)方法,并作为参数传入。
                   从而,调用方Activity可以获取到Service返回的Binder对象,进而通过调用Binder对象的方法 在Service中执行一些逻辑。
               unBindService(ServiceConnection);//解除指定的绑定
(Service只是一个没有UI,运行在后台的组件而言,按照普通方式生成和注册的本地Service仍然是运行在app进程的主线程中的。
        只有远程Service才是运行在其它进程中,那需要写相应的aidl脚本并在AndroidManifest.xml文件中声明Service时进行相应处理。
    相应参考:android-Service和Thread的区别 - 路人浅笑 - 博客园)


1.直接启动
非常简单,一个方法启动,一个方法停止。
//指明Service目标
Intent intent = new Intent( xx.this, xxServcie.class );
//启动
startService( intent );
//停止
stopService( intent );

2.绑定形式:以代码和注释来说明

public class TestService extends Service {
    //Binder类,可视为
    private MyBinder extends Binder {
        public String test(){
            return "Hi,这串字符串是从TestService返回的!";
        }
    }

    MyBinder myBinder = new MyBinder();

    //Service第一次创建时,触发该方法
    public void onCreate(...){
        ...
    }

    //绑定成功时,触发该方法
    public Binder onBind(...){
        ...
        return myBinder;
    }

    //解除绑定时,触发该方法
    public void onUnbind(...){
        ...
    }

    //通过startService(intent)方式来启动Service时,会触发该方法
    public void onStartCommand(...){
        ...
    }

    //Service销毁时,会触发该方法
    public void onDestroy(...){
        ...
    }

}


public class TestAcitivity extends Activity {

    private ServiceConnection conn = new ServiceConnection(){
        //当与Service连接成功时触发该回调方法
        //上面Service类的onBind(...)返回的Binder对象,即为此方法中的Binder对象参数
        public void onServiceConnection(..., Binder binder){
            //重新转换回原对象类型,即可利用myBinder来与Service进行一系列信息交互和操作
            TestService.MyBinder myBinder = ( TestService.MyBinder ) binder;
            ...
        }

        //当连接断开时,触发该回调方法
        public void onServiceDisconnection(....){
            ...
        }
    }


    public void onCreate(...){
        //触发与Service的连接,以便将该Activity与Service绑定
        Intent intent = new Intent(TestActivity.this, TestService.class );
        bindService( intent, conn, 【连接方式】 );

        //断开与Serviced的连接,以便将该Activity与Service解除绑定
        unbindService( conn );
    }

    //其它方法此处省略...............
}


参考资料:
           Android Service(一)--浅谈Service - Android移动开发技术文章_手机开发 - 红黑联盟
           android中Service使用详解 - ThinkDo的博客 - 博客频道 - CSDN.NET
           Android Service完全解析,关于服务你所需知道的一切(上) - 郭霖的专栏 - 博客频道 - CSDN.NET
           Android 中的 Service 全面总结 - newcj - 博客园