首页 > 代码库 > Service和Activity交互之广播方式
Service和Activity交互之广播方式
一.使用场景
如果要通知多个Activity,广播较为适合.但广播较为耗费性能.
二.Broadcast更新Activity中的UI
1.新建一个接口OnUpdateUI
public interface OnUpdateUI { void updateUI(String i); }
2.BroadcastReceiver代码
public class MyBroadcast extends BroadcastReceiver { OnUpdateUI onUpdateUI; @Override public void onReceive(Context context, Intent intent) { String progress = intent.getStringExtra("progress"); onUpdateUI.updateUI(progress); } public void SetOnUpdateUI(OnUpdateUI onUpdateUI){ this.onUpdateUI = onUpdateUI; } }
3.Activity中代码:
public class MainActivity extends Activity { public static final String FLAG = "UPDATE"; MyBroadcast myBroadcast; TextView tip; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tip = (TextView)findViewById(R.id.tip); myBroadcast = new MyBroadcast(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(FLAG); registerReceiver(myBroadcast, intentFilter); intent = new Intent(this, MyService.class); // 更新UI myBroadcast.SetOnUpdateUI(new OnUpdateUI() { @Override public void updateUI(String i) { tip.setText(i); } }); } protected void myClick(View v){ // 发送广播 if( v.getId() == R.id.btn ){ Intent intent = new Intent(); intent.setAction(FLAG); intent.putExtra("progress", System.currentTimeMillis()+""); sendBroadcast(intent); } // 启动服务 if (v.getId() == R.id.btn2){ Intent intent = new Intent(this, MyService.class); startService(intent); } } @Override protected void onDestroy() { unregisterReceiver(myBroadcast); stopService(intent); super.onDestroy(); } }
三.Service发送广播,广播更新Activity中UI
Service发送广播
Intent it = new Intent(); it.setAction(MainActivity.FLAG); it.putExtra("progress", i+""); sendBroadcast(it);
Service和Activity交互之广播方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。