Android編程心得-Service資料繫結初步

來源:互聯網
上載者:User

在Android裡,Service的資料繫結是一種重要的用法,我們知道Service與Activity一樣是運行在當前應用進程的主線程裡面的,他們之間互動的方式有多種,下面我來介紹一下如何使用資料繫結的方法通過Service向Activity互動資料 1.首先我們要定義一個介面,介面裡定義我們需要實現的方法 

public interface ICount {              public int getcount();                }  

 

 2.接下來我們需要一個Service的子類實現本介面,定義一個ServiceBinder的內部類,通過它的對象來綁定資料,要注意的是我們如果要進行耗時操作的話,仍然需要在Service中建立線程,Service自身就是運行在主線程中的。還有一個就是OnBind的傳回值是IBinder,但是這裡我使用ServiceBinder對象是繼承Binder的,那為什麼這裡可以這麼寫呢?因為Binder是Base class for a remotable object, the core part of a lightweight remote procedure call mechanism defined by IBinder,是直接從IBinder這裡的直接子類。 
public class BackGroundService extends Service implements ICount {      private boolean disable;  //線程是否執行的標識位      private int count;      //計數      private ServiceBinder serviceBinder = new ServiceBinder();            public class ServiceBinder extends Binder implements ICount {          @Override          public int getcount() {              // TODO Auto-generated method stub              return 0;          }          }            @Override      public IBinder onBind(Intent intent) {          // TODO Auto-generated method stub          return serviceBinder;      }              @Override      public void onCreate() {          // TODO Auto-generated method stub          super.onCreate();          new Thread(new Runnable() {              // @Override              public void run() {              while (!disable) {              try {              Thread.sleep(1000);              } catch (InterruptedException e) {              }              count++;              System.out.println("CountService Count is " + count);              }              }              }).start();      }        @Override      public int onStartCommand(Intent intent, int flags, int startId) {          // TODO Auto-generated method stub            return super.onStartCommand(intent, flags, startId);      }        @Override      public int getcount() {          return count;          // TODO Auto-generated method stub                }                    @Override      public void onDestroy() {          // TODO Auto-generated method stub          this.disable = true;  //      Log.v(" CountService ", " on destroy ");          System.out.println("Service destroy...");          super.onDestroy();      }    }  

 

  3.定義完了Service這一部分的內容,接下來就需要在AndroidManifest.xml中註冊了,需要注意的是這裡不僅要對我們包類的Service進行聲明,同時還需要聲明intent的過濾器 
<service android:name="com.yqc.testservice.BackGroundService">      <intent-filter>          <action android:name="com.yqc.testservice.BackGroundService" />      </intent-filter>  </service>  

 

 4.定義完畢以後,接下來需要在Activity中的互動部分了,剛才在設定檔中定義的Intent的過濾器這裡就用到了,在bindService方法中,這就是他的一個參數,然後通過ServiceConnetion的對象與Service建立串連並取得背景參數。 
public class MainActivity extends Activity {        Button btn_start;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            this.bindService(new Intent("com.yqc.testservice.BackGroundService"),                  this.serviceConnection, BIND_AUTO_CREATE);            btn_start = (Button) findViewById(R.id.btn_start);          btn_start.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                }          });      }          @Override      protected void onDestroy() {          // TODO Auto-generated method stub          this.unbindService(serviceConnection);          System.out.println("Activity Destroy...");          super.onDestroy();      }        private ICount countentity;        private ServiceConnection serviceConnection = new ServiceConnection() {          @Override          public void onServiceConnected(ComponentName name, IBinder service) {              // TODO Auto-generated method stub              countentity = (ICount) service;              System.out.println(" CountService on serivce connected, count is "                      + countentity.getcount());          }            @Override          public void onServiceDisconnected(ComponentName name) {              // TODO Auto-generated method stub              countentity = null;          }      };  }  

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.