0

I am building a simple producer-consumer usecase in android with following features:

  1. Main Activity has a Fullscreen ImageView
  2. Producer service populates a queue with images and time for which each image must be viewed
  3. Consumer thread reads these images and sets the imageView for time mentioned.

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

How do I update imageView from PlaylistConsumer class ?

jay
  • 1,982
  • 2
  • 24
  • 54

1 Answers1

0

First you need to 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);

then, in the activity, create and register Broadcast receiver

//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();
}

I also recommend to use LocalBroadcastManager to register and send broadcasts.

Community
  • 1
  • 1
Fen1kz
  • 1,050
  • 12
  • 24