簡體   English   中英

將數據從活動傳遞到IntentService(Android SDK)

[英]Passing data from Activity to IntentService (Android SDK)

我創建了在整個應用程序期間都在后台運行的服務。
我為此選擇了一個IntentService
對我而言, intent.putExtra(....)僅在啟動服務時起作用。
我的問題是,有時我不僅要在開始時就將數據從Activity傳遞到IntentService
謝謝

只需通過啟動將數據傳輸到IntentService ,因為IntentService在整個應用程序生命周期中始終只有一個實例。

您可以使用綁定接口與服務公共方法進行交互。

從文檔:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM