我正在android中构建一个简单的生产者 - 消费者用例,具有以下功能:
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?
答案 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);
//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注册和发送广播。