MessagerService总结
一、整体工程图
二、messenger_service_binding.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
- android:gravity="center_horizontal"
- android:layout_width="match_parent" android:layout_height="match_parent">
- <TextView
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:layout_weight="0"
- android:paddingBottom="4dip"
- android:text="@string/messenger_service_binding"/>
- <Button android:id="@+id/bind"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="@string/bind_service">
- <requestFocus />
- </Button>
- <Button android:id="@+id/unbind"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="@string/unbind_service">
- </Button>
- <TextView android:id="@+id/callback"
- android:layout_width="match_parent" android:layout_height="wrap_content"
- android:layout_weight="0"
- android:gravity="center_horizontal" android:paddingTop="4dip"/>
- </LinearLayout>
三、AndroidManifest.xml
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.jltxgcy.messengerservice"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name=".MessengerServiceActivities"
- android:label="@string/title_activity_messenger_service" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service
- android:name=".MessengerService">
- </service>
- </application>
- </manifest>
四、MessengerServiceActivities.java
- package com.jltxgcy.messengerservice;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- 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;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MessengerServiceActivities extends Activity{
- Messenger mServiceMessage = null;
- boolean mIsBound;
- TextView mCallbackText;
- class IncomingHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MessengerService.MSG_SET_VALUE:
- mCallbackText.setText("Received from service: " + msg.arg1);
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
- final Messenger mMessenger = new Messenger(new IncomingHandler());
- private ServiceConnection mConnection = new ServiceConnection() {
- public void onServiceConnected(ComponentName className,
- IBinder service) {
- mServiceMessage = new Messenger(service);
- mCallbackText.setText("Attached.");
- try {
- Message msg = Message.obtain(null,
- MessengerService.MSG_REGISTER_CLIENT);
- msg.replyTo = mMessenger;
- mServiceMessage.send(msg);
- msg = Message.obtain(null,
- MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
- mServiceMessage.send(msg);
- } catch (RemoteException e) {
- }
- }
- public void onServiceDisconnected(ComponentName className) {
- mServiceMessage = null;
- Log.d("jltxgcy", "onServiceDisconnected");
- }
- };
- void doBindService() {
- bindService(new Intent(MessengerServiceActivities.this,
- MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
- mIsBound = true;
- }
- void doUnbindService() {
- if (mIsBound) {
- if (mServiceMessage != null) {
- try {
- Message msg = Message.obtain(null,
- MessengerService.MSG_UNREGISTER_CLIENT);
- msg.replyTo = mMessenger;
- mServiceMessage.send(msg);
- } catch (RemoteException e) {
- }
- }
- unbindService(mConnection);
- mIsBound = false;
- }
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.messenger_service_binding);
- Button button = (Button)findViewById(R.id.bind);
- button.setOnClickListener(mBindListener);
- button = (Button)findViewById(R.id.unbind);
- button.setOnClickListener(mUnbindListener);
- mCallbackText = (TextView)findViewById(R.id.callback);
- }
- private OnClickListener mBindListener = new OnClickListener() {
- public void onClick(View v) {
- doBindService();
- }
- };
- private OnClickListener mUnbindListener = new OnClickListener() {
- public void onClick(View v) {
- doUnbindService();
- }
- };
- }
五、MessengerService.java
- /*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package com.jltxgcy.messengerservice;
- import java.util.ArrayList;
- import android.app.NotificationManager;
- 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;
- import android.widget.Toast;
- public class MessengerService extends Service {
- private ArrayList<Messenger> mClients = new ArrayList<Messenger>();
- private int mValue = 0;
- public static final String TAG = "jltxgcy";
- public static final int MSG_REGISTER_CLIENT = 1;
- public static final int MSG_UNREGISTER_CLIENT = 2;
- public static final int MSG_SET_VALUE = 3;
- class IncomingHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_REGISTER_CLIENT:
- mClients.add(msg.replyTo);
- break;
- case MSG_UNREGISTER_CLIENT:
- mClients.remove(msg.replyTo);
- break;
- case MSG_SET_VALUE:
- mValue = msg.arg1;
- for (int i=mClients.size()-1; i>=0; i--) {
- try {
- mClients.get(i).send(Message.obtain(null,
- MSG_SET_VALUE, mValue, 0));
- } catch (RemoteException e) {
- mClients.remove(i);
- }
- }
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
- final Messenger mMessenger = new Messenger(new IncomingHandler());
- @Override
- public void onCreate() {
- Log.d(TAG, "onCreate");
- }
- @Override
- public void onDestroy() {
- Log.d(TAG, "onDestroy");
- }
- @Override
- public IBinder onBind(Intent intent) {
- Log.d(TAG, "onBind");
- return mMessenger.getBinder();
- }
- @Override
- public boolean onUnbind(Intent intent) {
- Log.d(TAG, "onUnbind");
- return super.onUnbind(intent);
- }
- }
六、详解
点击Bind Service,Logcat显示如下:
Service中:final Messenger mMessenger = new Messenger(new IncomingHandler()); onBind方法中mMessenger.getBinder()
Activity中, final Messenger mMessenger = new Messenger(new IncomingHandler()); onServiceConnected中mServiceMessage = new Messenger(service);
onBind方法中返回一个IBinder对象,onServiceConnected中,通过IBinder对象获取到了Messager对象。再通过msg.replyTo建立通信。
点击Unbind Service,Logcat显示如下:
运行结果如下:
获取message的方法:
- 1、Message msg =new Message();
- msg.arg1=x;
- msg.arg2=x;
- msg.obj=x;
- msg.replyTo=x;
- msg.what=x;
- msg.setData(Bundle bundle);
- 2、Message msg =Messge.obtain(Handler h, int what, int arg1, int arg2, Object obj);
- msg.replyTo=x;
- msg.setData(Bundle bundle);
MessagerService总结的更多相关文章
- Android面试,与Service交互方式
五种交互方式,分别是:通过广播交互.通过共享文件交互.通过Messenger(信使)交互.通过自定义接口交互.通过AIDL交互.(可能更多) Service与Thread的区别 Thread:Thre ...
- SpringBoot | 第三十八章:基于RabbitMQ实现消息延迟队列方案
前言 前段时间在编写通用的消息通知服务时,由于需要实现类似通知失败时,需要延后几分钟再次进行发送,进行多次尝试后,进入定时发送机制.此机制,在原先对接银联支付时,银联的异步通知也是类似的,在第一次通知 ...
- android 应用程序与服务端交互
http://www.cnblogs.com/freeliver54/archive/2012/06/13/2547765.html 简述了Service的一些基础知识以及Service和Thread ...
随机推荐
- 【转】如何删除一个repository(仓库)
原文网址:http://my.oschina.net/anna153/blog/377758?p=1 如何删除自己创建的一个项目,我浏览了一下github网站,确实不太容易找到删除功能.这里介绍一下啊 ...
- 流风ASP.NET框架商业版-工作流1.0简介
流风ASP.NET框架商业版-工作流1.0简介 工作流简介 在流风ASP.NET框架商业版1.0推出后,就有集成工作流的想法,但是由于工作繁忙和其他事情的耽搁,时隔半年之久工作流1.0的版本才姗姗来迟 ...
- java内存模型和线程
概述 多任务的处理在现在的计算机中可以说是"标配"了,在许多的情况下,让计算机同时做几件事情,不仅是因为计算机的运算能力的强大,还有一个重要的原因是:cpu的运算速度和计算机的存储 ...
- Day56
今天干啦啥呢 早上七点起来 天气冷了真起不来啊 再坚持坚持就好了 今天上午九点开始考数据库 我去 大学四年第一次感觉到这样的爽 作弊的爽啊 也没有完全的作弊啦 是开卷考试,反正做的很顺利了. 我和胡 ...
- Spring 源码解读 推荐流程
Spring源代码解析(一):IOC容器:http://www.javaeye.com/topic/86339 Spring源代码解析(二):IoC容器在Web容器中的启动:http://www.ja ...
- Wikioi 1080一维树状数组
半个月时间最终把那些杂七杂八的学完了,尽管学完也,也仅仅是有了个模板,自己手敲还是不太行.所以如今開始要疯狂刷题了! ! .!!! 这题裸的树状数组.曾经写那道<敌兵布阵>的时候写过,所以 ...
- [Redux] React Todo List Example (Filtering Todos)
/** * A reducer for a single todo * @param state * @param action * @returns {*} */ const todo = ( st ...
- Qt 界面使用自己定义控件 "提升为"
1.效果图 我做了一个很easy的样例,一个能够显示颜色的QLabel,边上有个button,点击,跳出颜色选取的Dialog,然后选择一个颜色.这个QLabel会变成什么颜色. 2.ColorLab ...
- asp.net服务器向客户端弹出对话框,但不使页面边白板
1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: ...
- 老生常谈的Javascript作用域问题
在前端学习中,作用域这个问题一直被广泛提起,什么是作用域,什么又是作用域链?在Javascript中,怎么去理解这些概念都是学好这门语言的关键,所以在学习前端开发的过程中,我需要也很有必要去学习和总结 ...