Android 绑定服务

来源:互联网 发布:信捷plc xc3编程软件 编辑:程序博客网 时间:2024/06/05 05:33


Service是没有界面的,一直在后台运行,适合执行一些无须与用户交互,长期运行的任务;例如:后台播放音乐、后台下载等。

服务开启有2种方式,startService()和bindService(),也可以混合使用;

Activity活动startService()后就与没什么关联了,当程序销毁时,服务还在运行,所以使用startService()后需要在Activity的onDestory()或onStop()方法中stopService()

(即手动关闭该服务);

绑定服务用法:

首先自定义一个服务,里面定义一个内部类继承Binder类;代码如下:

public class MyService extends Service{

    private MyBinder mBinder = new MyBinder();

    public class MyBinder extends Binder{

        MyService getService(){

            return MyService.this;

         }

    } 


     public IBinder onBinder(Intent intent){

            return mBinder;

      }


      public int getRandom(int  value){

         return new Random().nextInt(value);

       }

}


然后在activity中定义ServiceConnection 对象,绑定服务

private ServiceConnection sc = new ServiceConnection(){

    public void onServiceConnected(ComponentName name, IBinder service){

         MyService.MyBinder binder = (MyService.MyBinder)service;

         //获取Activity所绑定服务的对象

         myService =binder.getService();

    }

    public void onServiceDisConnected(ComponentName name){

   }

};

你可以在Activity创建时就绑定对象,也可以在点击按钮时绑定对象:

Intent intent = new Intent(MainActivity.this,MyService.class);

bindService(intent,sc,Service.BIND_AUTO_CREATE);


然后你就可以使用myService对象访问服务里面的方法了,最好先判断myService是否为空,即有没有初始化获取到了服务对象;


本文参考了网络上的一些资料自行测试的,如有谬误,还请指正。



原创粉丝点击