2
在Android官方開發人員指南的目的,Bound Service章,有關於它擴展了活頁夾本地粘合劑的例子,代碼是這樣的:的Android爲什麼要使用本地服務
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
,特別是因爲這是客戶端調用的方法:
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
我感到有點困惑了這樣一個簡單的動作,爲什麼我們需要把它放到硒起動轉矩?更重要的是,這個服務只是一個本地服務,只能在當前的應用程序中使用,而不能在其他應用程序中使用。當然,這種方法顯然可以作爲公開的方法放入任何類中,對於上述情況就足夠了。
我可以理解將文件下載代碼放入服務(或者IntentService更合適一些)的目的,它適用於服務的功能:運行長時間處理代碼。
但我不明白的是爲什麼我們需要這樣的本地服務?需要
謝謝!但是,您能否爲這個'客戶 - 服務器'案例提供一個例子?另外我想知道'使用callbakc獲取結果並在活動中執行操作'的用例和機制。 –
而且我可以理解客戶端和服務器的情況,當客戶端和服務器在不同的進程中時,如果客戶端和服務器處於相同的進程中,還有很多其他方式來進行通信,例如廣播,靜態變量,甚至他們可以調用彼此的方法直接,不是嗎? –