2016-07-21 6 views

答えて

2

SerivceからActivityにイベントを送信する方法はたくさんあります。
私はあなたに次の方法をお勧めします。

バインドとコールバック

私はバインドとコールバックは公式の方法だと思います。
Communication between Activity and Service
Example: Communication between Activity and Service using Messaging

EventBus

私はEventBusが簡単な方法だと思います。
活動に https://github.com/greenrobot/EventBus

(または任意の):

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インスタンスを保持している:

public class BusHolder { 

    private static EventBus eventBus; 

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

    private BusHolder() { 
    } 
} 

イベントは掲載:

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

があなたのサービスからのメッセージを送ります。

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

これが役立ちます。

0

サービスコンポーネントの代わりにオブジェクトにデータを格納するのは良いことだと思っていないので、一時的なデータを格納するようなデータベースを使用する必要があります。ユーザーがアプリケーションに戻ったかどうかは、オブジェクトが開発プロセス全体を通して避けるべきメモリをカバーするかどうかのように、オブジェクトにリスト全体のデータを格納することは冗長です。運が良かった。

+0

チャットのようなアプリの場合、デバイスにデータを保存する必要はありません – injecteer

+0

サービスはsqliteサーバー(android)にデータを挿入し、recyclerviewにも更新します。 –

関連する問題