通过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,那么对应的 ...
随机推荐
- 源码解读—Stack
Stack特性:先进后出.后进先出 java.util.Stack实现了这一数据结构. public class Stack<E> extends Vector<E>,Sta ...
- poj 2632 Crashing Robots
点击打开链接 Crashing Robots Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 6655 Accepted: ...
- 翻译:为 URL Rewrite 模块创建重写规则
原文名称:Creating Rewrite Rules for the URL Rewrite Module 原文地址:http://www.iis.net/learn/extensions/url- ...
- PMP考试--成本管理中常用的概念
如果你对项目管理.系统架构有兴趣,请加微信订阅号"softjg",加入这个PM.架构师的大家庭 净现值(NPV) Net Present Value 在项目计算期内,按行业基准 ...
- 安装Oracle软件
1.安装linux操作系统和VMware Tools 2.创建组和用户,以root用户运行以下命令: groupadd -g 1000 oinstall groupadd -g 1001 dba us ...
- Python批量插入SQL Server数据库
因为要做性能测试,需要大量造数据到数据库中,于是用python写了点代码去实现,批量插入,一共四张表 简单粗暴地插入10万条数据 import pymssql import random __auth ...
- JS实现联想输入(一)
这里是我们的项目中的一个使用JS实现联想输入的功能代码,在此做个小的记录并且将它分享给大家希望对园中的朋友有用! 我将分享三段都非常简单的代码,仅仅作为个人的一点小小的积累而已! 1:后台的Actio ...
- 学习总结 java Iterator迭代器练习
package com.hanqi.jh; import java.util.*; public class Text3 { public static void main(String[] args ...
- python函数基础以及函数参数简解
python中函数分为函数.内置函数Python所有的内置函数 自定义函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. ...
- PAT1007
#include<stdio.h>#include<vector>#include<algorithm>using namespace std; int main( ...