[英]Service call backs to activity in android
我有一個后台服務運行和一個與服務交互的客戶端。
當客戶端請求某些操作時,服務執行它並且它應該將結果發送回活動(客戶端)。
我知道如何在活動中調用服務方法並使用回調我們可以實現我想要做的事情。 但我無法理解Api演示(remoteservice)中提供的回調機制和代碼示例。
有人可以解釋這個服務回調是如何工作的; 或者使用更簡單的機制可以實現的任何東西。
這是流程
創建調用服務的意圖。 您可以startService()
或BindService()
與BIND_AUTO_CREATE
一旦服務結合,它將創建一個隧道與客戶端進行通信,即IBinder
接口。 這將由您的AIDL接口實現使用並返回IBinder
private final MyServiceInterface.Stub mBinder = new MyServiceInterface.Stub() {
public int getNumber() {
return new Random().nextInt(100);
}
};
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
return mBinder;
}
一旦它返回mBinder
,您將在客戶端中創建的ServiceConnection
將被回調,您將通過此方式獲得服務接口
mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = MyServiceInterface.Stub.asInterface(service);
};
現在你有了mService
接口來調用和檢索任何服務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.