Activity与Service通信
来源:互联网 发布:icmp协议端口号 编辑:程序博客网 时间:2024/05/16 09:15
Activity向Service发消息(在Service运行过程中):
在Service中实现一个继承自Binder的内部类,
private final IBinder binder = new LocalBinder(); public class LocalBinder extends Binder { public LogService getService() { return LogService.this; } public void stopRunning(){isRunning = false;}} @Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn binder;}
在Activity中获取这个binder实例:
private boolean isConnected; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub isConnected=false; } @Override public void onServiceConnected(ComponentName arg0, IBinder binder) { // TODO Auto-generated method stub localBinder = (LocalBinder) binder; logSvc =((LocalBinder) localBinder).getService(); isConnected=true; } };
启动服务并bind:
startService(intent);doBindService();
即可通过这个binder实例与运行中的service通信:
localBinder.stopRunning();
Service向Activity发消息:
利用BroadcastReceiver。在Activity中注册:
mReceiver = new timeUpReceiver();IntentFilter filter = new IntentFilter();filter.addAction("com.zhuming.broadcast.timeup");this.registerReceiver(mReceiver, filter);public class timeUpReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { toggleBtn.setChecked(false); toggleTxt.setText("等待超时,请重新开启服务"); }}
在Service中发送广播:
Intent intent = new Intent("com.zhuming.broadcast.timeup");sendBroadcast(intent);
0 0
- Activity与Service通信
- Service与Activity通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Service与Activity通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Activity与Service通信
- Service与Activity通信
- Service与Activity进行通信
- (转)Activity与Service通信
- android activity与service通信
- 常用正则表达式大全
- 入秋心血管病患者5点生活提示
- VC++中调用MATLAB中的数据
- Til the Cows Come Home - POJ 2387 Dijkstra
- view
- Activity与Service通信
- 求最大子段和的一些算法
- web开发设计--JS学习之通过ID获取元素
- hadoop坏境搭建
- 选择排序算法C语言实现
- poj 3207 2-SAT
- 简学lingo(四)——实例篇
- BroadcastReceiver trying to return result during a non-ordered broadcast
- uva 11258 - String Partition