在Android开发的时候必然少不了UI的更新,来保证用户的体验和交互。如果在主界面就很好更新,可是有时候总会遇到后台服务和ui交互 要求UI进行更新。
最好的办法就是可以使用广播来更新,也可以使用bindservice的返回IBinder来实现。
要用广播更新UI肯定要自己定义一个广博类继承于BroadcastReceiver
由于要更新UI所以定义为Activity内部类方便操作
但是广播只能用动态注册了
例如我自己写的音乐播放
我在MainActivity中定义了一个广播类
public class MusicReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int pc = intent.getIntExtra("process",-1);
if (pc!=-1){
process = pc;
return;
}
int position = intent.getIntExtra("position",-1);
if (position!=-1){
itemPosition = position;
adapter.setFocusPos(itemPosition);
binding.musicName.setText(musiclist.get(itemPosition).getMusicName());
updateTime(process,musiclist.get(itemPosition).getMusicDuration());
// updateTime(0,musiclist.get(itemPosition).getMusicDuration());
return;
}
isPlaying = intent.getBooleanExtra("isPlay",false);
if (isPlaying){
binding.btnPlay.setImageResource(R.drawable.pause);
}else {
binding.btnPlay.setImageResource(R.drawable.play);
}
}
}
然后在
oncreate方法中动态注册
private void registerBroadcast(){ //动态注册
recevicer = new MusicReceiver();
IntentFilter filter=new IntentFilter("com.Music_Control");//Intent的action
registerReceiver(recevicer,filter);
}
然后只需要在你想要更新UI的地方发送广播就可以了
例如
Intent intent=new Intent();
intent.setAction("com.Music_Control");//和代码注册时的IntentFilter filter=new IntentFilter("com.change_the_UI");对应
intent.putExtra("position", musicManager.getCurrentindex());
//intent.putExtra("process",musicManager.getCurrentPosition());
sendBroadcast(intent);