Yes, the problem is that Service run in MainThread (UI thread by default). you need to write data asynchronously on background thread. Notice, that Realm instance is thread dependent and it has to be obrained and released in single write transaction.
Consider using IntentService - it has background thread by default, or, use rxJava library for organizing background job - it's the simplest way.
Here is a code how it can be done:
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…