2016-11-21 45 views
-1

我在每個位置更改偵聽器的LocationService類中編寫realm db,並在Activity中列出此更改以更新UI。最初它工作正常,但是當realm db中的條目數量超過2K時,它會開始阻止UI。任何人都請建議。從導致UI塊的服務類中編寫領域

+2

*請人建議* ...好像你需要改變你的代碼... – Selvin

+0

喔,謝謝Selvin ...而不是簡單地降如果你知道一些事情,你應該給我一個想法。我不想爲此使用IntentService。 – Vid

+2

反而咆哮,你應該提供你的代碼...大多數程序員不使用魔法球,所以沒有代碼很難說什麼是問題... – Selvin

回答

1

是的,問題是服務運行在MainThread(UI線程默認情況下)。你需要在後臺線程上異步寫入數據。請注意,Realm實例是線程相關的,它必須在單個寫入事務中被取消並釋放。 考慮使用IntentService - 默認情況下它具有後臺線程,或者使用rxJava庫來組織後臺作業 - 這是最簡單的方法。 這裏是一個代碼,它是如何做到:

PublishSubject<Location> locationSource = PublishSubject.create(); 

     // bind to location source for receiving locations 
     Observable<Integer> saveToDbTask = 
     locationSource.asObservable() 
       // this line switches execution into background thread from embedded thread pool 
       .observeOn(Schedulers.computation()) 
       .map(location -> { 
        int result -> saveLocationToDb(location); 
        return result; 
       }); 

     // subscribe to that task when you start 
     Subscription subscription = saveToDbTask.subscribe(t -> { 
      Log.i(LOG_TAG, "Result: " + t); 
     }); 

     // unsubscribe when it is no longer needed 
     if (null != subscription && !subscription.isUnsubscribed()){ 
      subscription.unsubscribe(); 
      subscription = null; 
     } 

     // tunnel location from your FusedLocationApi's callback to pipeline: 
     Location loc = new Location(..); 
     locationSource.onNext(loc); 
+0

謝謝亞歷克斯,你是對的。然而,我的老闆讓我不要使用IntentService :-(。 – Vid

+3

然後創建普通服務,將位置更新回調綁定到PublishSubject ,訂閱它,並將其保存到後臺線程領域 –

+0

我已更新回答 –