Activity和Service之间通过handler传递数据
2016-03-03 12:02
363 查看
在写音乐播放器的时候用到了这个东西,相当于Activity中把mHandler用Messenger这个信封包裹着传递到了到了Service。Service拿到这个信封,信封里面装着mHandler,告诉service往里面装信息,然后信封再邮寄给mHandler。
Activity中的主要代码:
1.开启我的服务的方法
Service中接收Activity中传递过来的messager信封,在Service的的startCommand()方法中:
Activity中的主要代码:
1.开启我的服务的方法
private void startMyService(String option, String path) { Intent service = new Intent(this, MyService.class); service.putExtra("option", option); service.putExtra("messenger", new Messenger(mHandler)); service.putExtra("path", path); startService(service); }2,Activity中的handler
private Handler mHandler = new Handler() { // 接收结果,刷新界面 public void handleMessage(Message msg) { switch (msg.what) { case 1: break; case 2: break; } }; };
Service中接收Activity中传递过来的messager信封,在Service的的startCommand()方法中:
@Override public int onStartCommand(Intent intent, int flags, int startId) { String option = intent.getStringExtra("option"); if (mMessenger == null) { mMessenger = (Messenger) intent.getExtras().get("messenger"); } return super.onStartCommand(intent, flags, startId); }下面这个方法里面用到了Timer,在里面一直执行向Activity中的mHandler发送数据。
public void onPrepared(MediaPlayer mp) { if (mTimer == null) { mTimer = new Timer(); } /** * @Params task the task to schedule. delay amount of time in * milliseconds before first execution. @Params period amount of * time in milliseconds between subsequent executions. */ mTimer.schedule(new TimerTask() { @Override public void run() { // 1.准备好的时候告诉activity,当前歌曲的总时长 int currentPosition = mPlayer.getCurrentPosition(); int duration = mPlayer.getDuration(); Message message = Message.obtain(); message.what = Constants.MSG_ONPREPARED; message.arg1 = currentPosition; message.arg2 = duration; try { mMessenger.send(message); } catch (RemoteException e) { e.printStackTrace(); } } }, 0, 1000); }
相关文章推荐
- 【Data Cluster】真机环境下MySQL数据库集群搭建
- Java IO读写
- px像素如何转为dip设备独立像素设备独立像
- MVC与MVP以及MVVM的简介与理解
- 【Big Data】HADOOP集群的配置(二)
- macx操作系统下maven tools.jar问题解决办法
- RedBase SQL解析源码分析
- Ajax技术
- wordpress去掉评论响应式图片srcset属性
- 卸载Visual Studio
- Android Camera API2.0下全新的Camera FW/HAL架构简述
- 【Big Data】HADOOP集群的配置(一)
- Lists the predefined ANSI/ISO C99 and Microsoft C++ implementation preprocessor macros.
- iOS Gif图片展示N种方式(原生+第三方)
- eclipse控制台输出重定向到文件
- Qt添加系统托盘
- http通信,Android Gzip压缩解压
- CQRS框架:AxonFramework 之 Hello World
- SCOI2003【严格n元树】
- Request获取用户真实IP