10天学通Android开发(2-3)-核心组件Service绑定

发布时间:2020-10-16 13:50:49 作者:wanxl
来源:网络 阅读:624

通过startService开启的服务,当访问者关闭时,服务仍然存在;访问者需要与服务进行通信,则我们需要将访问者与服务进行绑定; 

如果使用Context.bindService()方法启动服务,则在服务未创建时,系统会调用服务的onCreate()方法,接着调用onBind()方法,这时就访问者与服务已经绑定了,主程序销毁时服务也会终止。

1)绑定服务时,会自动创建服务。

2)如果创建后并启动后再绑定,不会重新创建,一个Service只有一个实例

3)同时启动和绑定服务时,解除绑定服务,但不会销毁关闭服务的,必须解除绑定并停止服务。

4)通过StartService启动服务,当前Activity销毁,服务不会停止,通过BindService启动服务,当前Activity销毁,服务停止。

 

绑定与解绑定服务

(1)Context.bindService(Intent service,ServiceConnectionconn,BIND_AUTO_CREATE);//绑定服务

(2)Context.unbindService(ServiceConnectionconn);

 

 

ServiceConnection

ServiceConnection为一个接口,用于绑定和解绑定IBinder,因此需要创建一个类实现它;

class XxxServiceConnectionimplements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {

//service为在onBind返回的IBinder
//
绑定Binder对象
}
@Override
public void onServiceDisconnected(ComponentName name) {
//
解绑定Binder对象
}
}

 

Service

class XxxService extendsService{

private IBinder binder = new

XxxBinder();

public IBinder onBind(Intent intent){

return binder;

}

public int fun(int a){

//服务提供的方法,但是不能直接调用

...

}

private class XxxBinderextends Binder implements IXxxBinder{

//面向接口编程

public return fun1(int a){

//对外暴露的API

return fun(a);

//内部调用Service的方法

}

}

}

 

案例:绑定服务

主要功能:Service实现不断输出123……的服务功能,Activity调用Service的公开方法,调出当时的一个值。继续上次服务的案例,增加绑定等功能。

  1. 打开activity_main.xml,添加两个命令按钮,绑定服务和解除绑定:

<Button

       android:id="@+id/btnBindService"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="绑定服务" />

 

   <Button

       android:id="@+id/btnUnbindService"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="解除绑定" />

2) MainActivity.java,添加相应代码:

定义两按钮:

 private Button btnBindService,btnUnbindService;

 

通过查找得到这两个按钮:

btnBindService=(Button)findViewById(R.id.btnBindService);        btnUnbindService=(Button)findViewById(R.id.btnUnbindService);

3)添加事件侦听器:

btnBindService.setOnClickListener(this);

btnUnbindService.setOnClickListener(this);

4)在onClick中添加判断分支:

case R.id.btnBindService:           bindService(serviceIntent,this,Context.BIND_AUTO_CREATE);

        break;

         case R.id.btnUnbindService:

            unbindService(this);

       break;

需要当前类实现ServiceConnection,加进继承ServiceConnection

publicclass MainActivity extends ActionBarActivity implementsOnClickListener, ServiceConnection {

同时产生了两接口方法,

成功绑定的方法:

@Override

   publicvoid onServiceConnected(ComponentName arg0, IBinder bind) {

      // TODO Auto-generCatedmethod stub

      System.out.println("onServiceConnected");

       

   }

 

解除绑定或Service崩溃时

   @Override

   publicvoid onServiceDisconnected(ComponentName name) {

      // TODO Auto-generatedmethod stub

      System.out.println("onServiceDisconnected");

   }

5onBind要指定返回值,否则绑定时,其实没有真正绑定onServiceConnected不会执行

定义内部类MyServiceBinder扩展自Binder

publicclass MyServiceBinder extends Binder{

      public MyServicegetService()

      {

          return MyService.this;//取得服务的实例

      }

   }

定义myservicebinder,并返回:

private final MyServiceBindermyservicebinder=new MyServiceBinder();

public IBinder onBind(Intent arg0) {

      // TODO Auto-generatedmethod stub

      System.out.println("onBind");     

     

      returnmyservicebinder;

   }

6)服务内添加一输出:

privateinti=0;

  

   publicvoid startTimer(){

      if(timer==null){

          timer=new Timer();

          task=new TimerTask(){

             @Override

             publicvoid run(){

                i++;

                System.out.println(i);

               

          }

      };

      timer.schedule(task,1000,1000);

      }

   }

  

publicvoid stopTimer(){

      if(timer!=null)

      {

          task.cancel();

          timer.cancel();

          task=null;

          timer=null;

      }

   } 

  

   private Timer timer=null;

   private TimerTask task=null;

  

 其中,每一秒钟执行:

timer.schedule(task,1000,1000);

7onCreateonDestroy添加startTimerstopTimer

publicvoid onCreate(){

      System.out.println("创建好了");

     

      startTimer();

      super.onCreate();

   }

  

   @Override

   publicvoid onDestroy(){

      System.out.println("被销毁了");

      stopTimer();

      super.onDestroy();

   }

8)取得服务实例:

publicclass MyServiceBinder extends Binder{

      public MyService getService()

      {

          return MyService.this;//取得服务的实例

      }

   }

9)公开一个方法,取得服务内部的数字(状态)

publicint getCurrentNum()

   {

      returni;

   }

10)回到主Activity,取得服务

定义变量:

private MyService myService=null;

取得实例:

publicvoid onServiceConnected(ComponentNamearg0, IBinder bind) {

      // TODO Auto-generCatedmethod stub

      System.out.println("onServiceConnected");

      myService=((MyService.MyServiceBinder) bind).getService();

     

   }

11)添加按钮

<Button

       android:id="@+id/btnGetCurrentNumber"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

        android:text="GetCurrentNum" />

定义按钮:

private Button btnGetCurrentNumber;

取得:

btnGetCurrentNumber=(Button)findViewById(R.id.btnGetCurrentNumber);

事件:

       btnGetCurrentNumber.setOnClickListener(this);

实现:

case R.id.btnGetCurrentNumber:

            if(myService!=null)

            {

               System.out.println("当前服务中的数字是"+myService.getCurrentNum());

            }

        break;


文献参考:

http://blog.csdn.net/xiazdong/article/details/7772914

http://www.cnblogs.com/andriod-html5/archive/2012/02/28/2539457.html

http://blog.163.com/cazwxy_12/blog/static/898763720122106483898/


推荐阅读:
  1. u3d开发培训要学哪些?
  2. 赛门铁克通配符SSL证书,一张通配型证书实现全站加密

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

service android roi

上一篇:C++使用htslib库读入和写出bam文件的实例

下一篇:Node.js(二)——模块与包管理工具

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》