2016-07-21 2 views

답변

2

Serivce에서 활동으로 이벤트를 보내려면 여러 가지 방법이 있습니다.
다음과 같은 방법으로하는 것이 좋습니다.

바인딩 및 콜백

나는 바인딩 및 콜백 공식 방법이라고 생각합니다.
Communication between Activity and Service
Example: Communication between Activity and Service using Messaging

EventBus

나는 EventBus 쉬운 방법이라고 생각합니다.
https://github.com/greenrobot/EventBus

활동에

(또는 경우) : 귀하의 서비스에서

public class DataSetUpdatedEvent { 
    //It is better to use database and share the key of record of database. 
    //But for simplicity, I share the dataset directly. 
    List<Data> dataset; 

    public DataSetUpdatedEvent(List<Data> dataset) { 
     this.dataset = dataset; 
    } 
} 

메시지 보내기 :

public class BusHolder { 

    private static EventBus eventBus; 

    public static EventBus getInstnace() { 
     if (eventBus == null) { 
      eventBus = new EventBus(); 
     } 
     return eventBus; 
    } 

    private BusHolder() { 
    } 
} 

이벤트 게시 :

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ... 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     BusHolder.getInstnace().register(this); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     BusHolder.getInstnace().unregister(this); 
    } 

    @Subscribe 
    public void onDatasetUpdated(DataSetUpdatedEvent event) { 
     //Update RecyclerView 
    } 
} 

BusHolder는 BusEvent 인스턴스를 보유하고 .

BusHolder.getInstnace().post(new DataSetUpdatedEvent(dataset)); 

이 정보가 도움이되기를 바랍니다.

0

임시 데이터를 저장하는 것과 같은 데이터베이스를 사용해야 할 수도 있습니다. 왜냐하면 서비스 구성 요소 대신 개체에 데이터를 저장하는 것이 좋다고 생각하지 않기 때문입니다. 사용자가 응용 프로그램으로 돌아 왔는지 여부와 같이 객체에 전체 목록 데이터를 저장하는 것은 중복 될 수 있습니다. 객체가 개발 과정에서 피해야하는 메모리를 충당하기 위해 사용됩니다. 행운을 빌어 요.

+0

채팅 용 앱용 기기에 데이터를 저장할 필요가 없습니다. – injecteer

+0

서비스는 sqlite 서버 (android)에 데이터를 삽입하고 recyclerview에서도 업데이트합니다. –

관련 문제