从消费者服务更新UI

时间:2016-04-28 09:16:02

标签: java android android-service android-service-binding

我正在android中构建一个简单的生产者 - 消费者用例,具有以下功能:

  1. 主要活动有一个全屏ImageView
  2. 生产者服务使用图像和时间填充队列,以便查看每个图像
  3. 消费者线程读取这些图像并将imageView设置为所提及的时间。
  4. MainActivity:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView myImageView = (ImageView) findViewById(R.id.imageView);
        Intent consumerServiceIntent = new Intent(this, PlaylistConsumer.class);
        startService(consumerServiceIntent);
    

    如何从PlaylistConsumer类更新imageView?

1 个答案:

答案 0 :(得分:0)

首先你需要send broadcast from your service

// somewhere in PlaylistConsumer, when it needs to update
Intent intent = new Intent();
intent.setAction(I_HAVE_CONSUMED_PLAYLIST); // I_HAVE_CONSUMED_PLAYLIST is public static final String
sendBroadcast(intent);

然后,在活动中,createregister广播接收器

//create
mReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
     ImageView myImageView = (ImageView) findViewById(R.id.imageView);
     //update myImageView here
   }
 };
//register
@Override
protected void onResume() {
     super.onResume();
     registerReceiver(mReceiver, new IntentFilter(PlaylistConsumer.I_HAVE_CONSUMED_PLAYLIST));
}
// unregister when paused
@Override
protected void onPause() {
    if(mReceiver != null) {
        unregisterReceiver(receiver);
        mReceiver = null;
    }
    super.onPause();
}

我还建议使用LocalBroadcastManager注册和发送广播。