通过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,那么对应的 ...
随机推荐
- C Primer Plus(第五版)6
第 6 章 C 控制语句 : 循环 在本章中你将学习下列内容 已经多次学过,没怎么标注 · 关键字: for while do while · 运算符: < > >= <= ! ...
- POJ 2096 【期望DP】
题意: 有n种选择,每种选择对应m种状态.每种选择发生的概率相等,每种选择中对应的每种状态发生的概率相等. 求n种选择和m种状态中每种至少发生一次的期望. 期望DP好别扭啊.要用倒推的方法. dp[i ...
- framMaker、Velocity模版引擎
1.一种模板文件,可以自动加载数据到模板里面展现. 类似:Velocity 2.使用场景 1.web开发模式 WEB-INF/view/vm 在互联网公司的开发都是基于vm的开发,其次就是使用JS的框 ...
- OC基础(2)
类与对象 类的设计 第一个OC类 对象方法的声明和实现 类方法的声明和实现 *:first-child { margin-top: 0 !important; } body > *:last-c ...
- H264-AVS POC理解
H264码流的输出顺序是编码顺序,所以在编码B帧的时候,由于B是双向预测,需要先编码后面编码帧P/I,这时候先输出I/P,后面才有B帧. 在解码段拿到相应的I/P帧后,不能马上丢到buffer lis ...
- 使用 Cocos2d-x 3.1.1 创建 Windows Phone 8 游戏开发环境
cocos2d-x 是目前流行的游戏游戏开发框架,目前最新的版本是 3.1.1, 网上有些教程已经比较老了,本文将会介绍如何使用最新的 3.1.1 创建 Windows Phone 8 开发环境. 本 ...
- 如何正确的使用Lerp In Unity
摘要 本文探讨如何用lerp实现近似的匀速旋转,当然如果运用本文给出的方法,使用slerp则可以实现匀速旋转,并指出Unity官方lerp示例代码的一些缺陷. 现有问题 比如四元数Lerp API: ...
- spark1.4的本地模式编程练习(1)
spark编程练习 申明:以下代码仅作学习参考使用,勿使用在商业用途. Wordcount UserMining TweetMining HashtagMining InvertedIndex Tes ...
- activity的android:name 设置问题
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com. ...
- IoGetDeviceObjectPointer .
从名字获得设备对象 驱动的起始地址,大小等信息.