通过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,那么对应的 ...
随机推荐
- [ZOJ 1003] Crashing Balloon (dfs搜索)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3 题目大意:给你a,b两个数,问当b由约数1到100组成时,a能否由其 ...
- 使用jaxp对比xml进行DOM解析
/*DOM解析编程 •遍历所有节点 •查找某一个节点 •删除结点 •更新结点 •添加节点 /* package cn.itcast.jaxp; import java.io.File; import ...
- maven搭建项目的时候,src/main/java无法建立的问题,提示信息The folder is already a source folder.(文件夹已经是源文件夹。)
原因:maven自己引的jdk包不对,需要重新引包 操作方式: 1.在项目上右击(或用快捷键ALT+ENTER),打开properties-->java builder path-->re ...
- Android开发-API指南-服务
Service 英文原文:http://developer.android.com/guide/components/services.html 采集(更新)日期:2014-12-23 原博客:htt ...
- 【PL/SQL练习】基本的PL/SQL语句
1.无变量匿名快 begin dbms_output.put_line('Hello World'); end; 2.有变量的匿名块,定义变量: declare v_ename ); v_sal ,) ...
- windows 创建服务提示失败 5 拒绝 访问拒绝
1.桌面创建文本,输入 sc create .....echo. & pause 保存,重命名为 .bat 2.右键该文件,管理员运行
- C#中List集合转换JSON
#region 将List<>转换为Json public string List2JSON(List<object> objlist, string classname) { ...
- ajax 跳入error的一些原因
先放一个标准的jquery的ajax代码: $.ajax({ type: 'POST', url: 'getSecondClassification', data: {"sort2" ...
- 在jQuery和JavaScript中,实现转跳
隐藏转跳,浏览器不产生历史记录(replace).代码片段: window.location.replace("http://insus.cnblogs.com"); 当然我们还不 ...
- Windows phone 8 学习笔记(7) 设备(转)
本节主要涉及到 Windows phone 8 手机支持的各类设备,包括相机.设备状态,振动装置等.还有各类感应器,包括磁力计.加速度器和陀螺仪.通过设备状态可以获取内存.硬件.电源.键盘等状态:通过 ...