Android之使用bindService啟動服務。

來源:互聯網
上載者:User

       一般情況下我們使用startService(Intent service)來啟動一個服務,但這種情況下無法得到Service對象的引用,通過bindService方法啟動服務則可以實現此功能。下面給一個小例子示範一下:


1.調用者

package com.zhf.local;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;/** * 此例的目的就是拿到MyService的引用,從而可以引用其內部的方法和變數 * @author Administrator * */public class LocalServiceActivity extends Activity {/** Called when the activity is first created. */private MyService myService;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Intent intent = new Intent(this, MyService.class);bindService(intent, connection, Context.BIND_AUTO_CREATE);}private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {myService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {myService = ((MyService.MyBinder) service).getService();System.out.println("Service串連成功");//執行Service內部自己的方法myService.excute();}};protected void onDestroy() {super.onDestroy();unbindService(connection);};}

2.服務者

package com.zhf.local;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class MyService extends Service {    private final IBinder binder=new MyBinder();@Overridepublic IBinder onBind(Intent intent) {return binder;}public class MyBinder extends Binder{MyService getService(){return MyService.this;}}public void excute(){System.out.println("通過Binder得到Service的引用來調用Service內部的方法");}@Overridepublic void onDestroy() {//當調用者退出(即使沒有調用unbindService)或者主動停止服務時會調用super.onDestroy();}@Overridepublic boolean onUnbind(Intent intent) {//當調用者退出(即使沒有調用unbindService)或者主動停止服務時會調用System.out.println("調用者退出了");return super.onUnbind(intent);}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.