通过messenger实现activity与service的相互通信
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zzw.testmessenger.MainActivity" > <Button
android:id="@+id/bind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="绑定" /> <Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="发送数据" /> <Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="加法" /> </RelativeLayout>
activity_main.xml
MainActivity:
package com.zzw.testmessenger; import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener {
Button bind, send, start;
ServiceConnection sc;
Messenger sender, receiver;
int sum;
Handler handler; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); bind = (Button) findViewById(R.id.bind);
bind.setOnClickListener(this);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(this); handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
int sum = (Integer) msg.obj;
Log.d("收到服务器传来的消息--->", sum + "");
}
}
};
//activity接收serviece的数据的接收者
receiver = new Messenger(handler);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bind:
bindService();
break;
case R.id.send:
sendMessageToService();
break;
case R.id.start:
StartService();
break;
}
} private void bindService() {
sc = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
//activity向serviece的发送数据的发送者
sender = new Messenger(service);
}
};
Intent intent = new Intent(MainActivity.this, MessengerService.class);
bindService(intent, sc, BIND_AUTO_CREATE);
} private void StartService() {
Intent it = new Intent(MainActivity.this, MessengerService.class);
startService(it);
} private void sendMessageToService() {
try {
Message msg = new Message();
int a = (int) (Math.random() * 20);
int b = (int) (Math.random() * 20);
int s[] = { a, b }; msg.what = 0;
msg.obj = s; // 设置一个Messenger receiver,receiver是提供给Service使用来给Activity响应的目标。
msg.replyTo = receiver;
sender.send(msg); Log.d("sendMessageToService", "发送成功----->");
} catch (RemoteException e) {
e.printStackTrace();
}
} @Override
protected void onDestroy() {
unbindService(sc);
Intent intent = new Intent(MainActivity.this, MessengerService.class);
stopService(intent);
super.onDestroy();
}
}
MessengerService:
package com.zzw.testmessenger; import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log; public class MessengerService extends Service {
private Messenger messenger, sender;
Handler handler;
int a, b, sum; @Override
public void onCreate() {
Log.d("MessengerSerivice", "onCreate");
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
int[] s = (int[]) msg.obj;
a = s[0];
b = s[1];
Log.d("从activity收到的msg", "a=" + a + " b=" + b);
}
//service向activity发送数据的发送者
sender = msg.replyTo;
}
};
//service接收activity的数据的接收者
messenger = new Messenger(handler);
} private void sendMessageToActivity(Messenger sender) {
try {
Message msg = new Message();
msg.what = 1;
msg.obj = sum;
sender.send(msg);
Log.d("sendMessageToActivity", "成功发送");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MessengerSerivice", "onStartCommand");
sum = a + b;
Log.d("在onStartCommand中算出的和", sum + "");
sendMessageToActivity(sender); return super.onStartCommand(intent, flags, startId);
} @Override
public IBinder onBind(Intent intent) {
Log.d("MessengerSerivice", "onBind");
return messenger.getBinder();
} }
通过messenger实现activity与service的相互通信的更多相关文章
- activity 与 service 之间的通信
activity和service通信:通过binder 举个我实际项目中的例子:在service中下载更新应用 首先是下载更新apk的service: public class UpdateVersi ...
- activity与service进程内通信
package com.example.binbin.testbinder; import android.app.Service; import android.content.Intent; im ...
- Android中Activity、Service和线程之间的通信
Activity.Service和线程应该是Android编程中最常见的几种类了,几乎大多数应用程序都会涉及到这几个类的编程,自然而然的,也就会涉及到三者之间的相互通信,本文就试图简单地介绍一下这三者 ...
- activity与service之间的通信方式
Activity之间的通信 1.activity与activity的通信可以通过Intent来封装数据,startActivityForResult()来实现,当跳转的activity调用finish ...
- 使用Messenger 从Activity发送数据到service 通过后台计算结果Log输出;
package com.lixu.messenger; import android.app.Activity; import android.app.Service; import android. ...
- Activity与Service通信(不同进程之间)
使用Messenger 上面的方法只能在同一个进程里才能用,如果要与另外一个进程的Service进行通信,则可以用Messenger. 其实实现IPC(Inter-Process Communicat ...
- Android Activity与Service的交互方式
参考: http://blog.csdn.net/gebitan505/article/details/18151203 实现更新下载进度的功能 1. 通过广播交互 Server端将目前的下载进度,通 ...
- Activity与Service通信的方式有三种:
在博客园看到的,看着挺不错的,借来分享下 继承Binder类 这个方式仅仅有当你的Acitivity和Service处于同一个Application和进程时,才干够用,比方你后台有一个播放背景音乐的S ...
- 201709012工作日记--activity与service的通信机制
service生命周期 Service主要包含本地类和远程类. Service不是Thread,Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 ...
随机推荐
- 解决WinForm(C#)中MDI子窗体最大化的问题
“用MDI方式打开一个子窗口体后,总是不能最大化显示,明明子窗口体的WindowState设置为Maximized?”,相信有很多人会遇到这的样问题,请按下面的方法设置即可使MDI子窗体最大化: 1. ...
- jstl的mavin依赖
pom.xml中加入 <!-- jstl支持 --><dependency> <groupId>javax.servlet</groupId> ...
- ARM的QT phonon 的移植
Phonon是QT提供的一套多媒体框架,提供多媒体播放图形界面和回放的功能,QT也是通过phonon来实现跨平台的多媒体播放.应用程序不需要关心多媒体播放到底是由什么实现的(如gstreamer.xi ...
- 题目1005:Graduate Admission
题目1005:Graduate Admission 时间限制:1 秒 内存限制:32 兆 特殊判题:否 题目描述: It is said that in 2011, there are about 1 ...
- HDU 4334 Trouble
Trouble Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- js面向过程改写成面向对象--通用方法
响亮的标题:一个万能的,保底的.面向过程改写成面向对象的方法 前提朗读:很多刚接触js面向对象的时候都不知道如何能快速的写出一个面向对象的程序,这个是必然的现象,不是每一位学js的一上来就会写面向对象 ...
- 网易音乐API
本次分析的是网易音乐API 歌曲搜索API:http://music.163.com/api/search/get/web?csrf_token= 需要用POST来获取 参数: Referer=htt ...
- Java虚拟机内存模型及垃圾回收监控调优
Java虚拟机内存模型及垃圾回收监控调优 如果你想理解Java垃圾回收如果工作,那么理解JVM的内存模型就显的非常重要.今天我们就来看看JVM内存的各不同部分及如果监控和实现垃圾回收调优. JVM内存 ...
- com学习前提必看
1) COM组件实际上是一个C++类,而接口都是纯虚类.组件从接口派生而来.我们可以简单的用纯粹的C++的语法形式来描述COM是个什么东西: class IObject { public: virtu ...
- SQL where 1=1的作用
浅谈where 1=1 1.简单理解的话where 1=1 永真, where 1<>1 永假 2.1<>1 的用处: 用于只取结构不取数据的场合 例如: ...