溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

10天學通Android開發(fā)(2-3)-核心組件Service綁定

發(fā)布時間:2020-10-16 13:50:49 來源:網絡 閱讀:629 作者:wanxl 欄目:移動開發(fā)

通過startService開啟的服務,當訪問者關閉時,服務仍然存在;訪問者需要與服務進行通信,則我們需要將訪問者與服務進行綁定; 

如果使用Context.bindService()方法啟動服務,則在服務未創(chuàng)建時,系統(tǒng)會調用服務的onCreate()方法,接著調用onBind()方法,這時就訪問者與服務已經綁定了,主程序銷毀時服務也會終止。

1)綁定服務時,會自動創(chuàng)建服務。

2)如果創(chuàng)建后并啟動后再綁定,不會重新創(chuàng)建,一個Service只有一個實例

3)同時啟動和綁定服務時,解除綁定服務,但不會銷毀關閉服務的,必須解除綁定并停止服務。

4)通過StartService啟動服務,當前Activity銷毀,服務不會停止,通過BindService啟動服務,當前Activity銷毀,服務停止。

 

綁定與解綁定服務

(1)Context.bindService(Intent service,ServiceConnectionconn,BIND_AUTO_CREATE);//綁定服務

(2)Context.unbindService(ServiceConnectionconn);

 

 

ServiceConnection

ServiceConnection為一個接口,用于綁定和解綁定IBinder,因此需要創(chuàng)建一個類實現它;

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實現不斷輸出1、2、3……的服務功能,Activity調用Service的公開方法,調出當時的一個值。繼續(xù)上次服務的案例,增加綁定等功能。

  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不會執(zhí)行

定義內部類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;

  

 其中,每一秒鐘執(zhí)行:

timer.schedule(task,1000,1000);

7onCreate、onDestroy添加startTimerstopTimer

publicvoid onCreate(){

      System.out.println("創(chuàng)建好了");

     

      startTimer();

      super.onCreate();

   }

  

   @Override

   publicvoid onDestroy(){

      System.out.println("被銷毀了");

      stopTimer();

      super.onDestroy();

   }

8)取得服務實例:

publicclass MyServiceBinder extends Binder{

      public MyService getService()

      {

          return MyService.this;//取得服務的實例

      }

   }

9)公開一個方法,取得服務內部的數字(狀態(tài))

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/


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI