bindservice的使用方法,bindservice用於繫結乙個服務。這樣當bindservice(intent,conn,flags)後,就會繫結乙個服務。這樣做可以獲得這個服務物件本身,而用startservice(intent)的方法只能啟動服務。
bindservice方式的一般過程:
1.新建service類bindservice。在bindservice類裡新建內部類mybinder,繼承自binder(binder實現ibinder介面)。mybinder提供方法返回bindservice例項。
publicclassmybinderextendsbinder
}例項化mybinder得到mybinder物件;
重寫onbind()方法:
@override
public ibinder onbind(intent intent)
2.在activity裡,例項化serviceconnection介面的實現類,重寫onserviceconnected()和onservicedisconnected()方法
serviceconnection conn=new serviceconnection()
@override
public void onservicedisconnected(componentname name)
3.在activity的oncreate()方法裡,新建intent,並繫結服務
intent intent=new intent(mainactivity.this,bindservice.class);
bindservice(intent, conn,bind_auto_create);
4.在activity的ondestroy裡面,新增
unbindservice(conn);
如果不加這一步,就會報android.app.serviceconnectionleaked: ******.mainactivity has leaked serviceconnection的異常。
bindservice()的執行過程如下:
bindservice(intent,conn,flag)->service:oncreate()->service:onbind()->activity:onserviceconnected()
code
bindService使用示例及問題說明
問題 用bindservice繫結乙個service,程式執行bindservice後,conn並未執行onserviceconnected介面 說明 bindservice用於繫結乙個服務。這樣當bindservice intent,conn,flags 後,就會繫結乙個服務。這樣做可以獲得這個服...
Android中bindService的使用方法
bindservice用於繫結乙個服務。這樣當bindservice intent,conn,flags 後,就會繫結乙個服務。這樣做可以獲得這個服務物件本身,而用startservice intent 的方法只能啟動服務。bindservice方式的一般過程 新建service類bindservi...
bindService的一些筆記
繫結本地服務的流程 1.在activity中呼叫bindservice 去繫結服務 bindservice intent new myconn bind auto create 需要傳遞乙個叫serviceconnection的介面引數,用來返回連個毀掉 當服務被成功繫結 當服務失去連線 2.在se...