Android 消息传递之Bundle的使用——实现object对象传输(二)
上面学习了线程通过Massage发送字符串消息,Handler接收字符串消息,这样的形式来更新ui,接下来,一起分享怎么把一个对象利用消息机制发送出去,让主线程接收来更新ui。
下面就利用一个服务Server,Handler,Activity,和一个对象类分享具体实现情况。
首先创建一个个类,什么都行。例如:
package dfrz.me.android.pcfileshare.bean; import java.io.Serializable; /**
* 描述:广告信息</br>
*/
public class ADInfo implements Serializable{ String id = "";
String url = "";
String content = "";
String type = ""; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String getType() {
return type;
} public void setType(String type) {
this.type = type;
} }
ADInfo
创建一个Activity父类:
import java.util.ArrayList; import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast; import dfrz.me.android.pcfileshare.service.MyHandler;
import dfrz.me.android.pcfileshare.service.MyService; public abstract class CustomActivity extends Activity { public static final int LENGTH_LONG = 1;
public static final int LENGTH_SHORT = 0;
public static String LOGCAT_KEY = "folder";
public static ArrayList<CustomActivity> activityList = new ArrayList<CustomActivity>();
public InputMethodManager inputMethodManager;
protected MyService.MyBinder binder = null; private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("file", "privateChat-->onServiceDisconnected");
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("file", "privateChat-->onServiceConnected");
binder = (MyService.MyBinder) service;
}
}; public void toast(String str,int i){
Toast.makeText(getApplicationContext(),str,i).show();
} /**
* onCreate方法中绑定服务。
* 添加接口等等一些操作。
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getSupportActionBar().hide();
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 启动activity时不自动弹出软键盘
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//获取系统键盘对象
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//将这个Activity加入到消息接收队列中
MyHandler.getInstance().registerActivity(this); activityList.add(this);
try {
while (!bindService(new Intent(this, MyService.class), connection, BIND_AUTO_CREATE)) ; } catch (Exception e) {
Toast.makeText(this, "服务器连接失败!", Toast.LENGTH_SHORT).show();
}
} @Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
//移除队列
MyHandler.getInstance().unRegisterActivity(this);
activityList.remove(this);
unbindService(connection);
} catch (Exception e) {
e.printStackTrace();
}
} public static void finishAll() {
for (Activity activity : activityList) {
if (!activity.isFinishing()) {
activity.finish();
}
}
} /**
* 初始化UI
*/
protected abstract void initView(); /**
* 初始化数据
*/
protected abstract void initData(); /**
* 监听事件
*/ protected abstract void initOnClick(); /**
* 接收消息
* @param bundle
*/
public abstract void recvMessageFormHandler(Bundle bundle); }
Activity父类
编写自己的Handle消息接收,和广播到每个活动界面上,前提是每个Activity都要继承父类,并实现接收消息的方法。
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log; import java.util.ArrayList; import dfrz.me.android.pcfileshare.base.CustomActivity; /**
* Created by Administrator on 2016/11/18.
*/
public class MyHandler extends Handler {
private ArrayList<CustomActivity> activityList; private Bundle bundle;
private MyHandler(){
activityList = new ArrayList<CustomActivity>();
} private static MyHandler instance = null; @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
bundle = msg.getData();
try {
if(activityList.size()>0){
for(CustomActivity customActivity:activityList){
//向每个customActivity内发送消息
customActivity.recvMessageFormHandler(bundle);
}
}
} catch (Exception e) {
// TODO: handle exception
}
} public static MyHandler getInstance(){
if(instance == null){
instance = new MyHandler();
}
return instance;
}
public void registerActivity(CustomActivity activity)
{
Log.d("HANDLER", "add "+activity.toString());
activityList.add(activity);
}
public void unRegisterActivity(CustomActivity activity){
Log.d("clientApp","remove"+activity.toString());
activityList.remove(activity);
}
}
MyHandler
为了方便发送不同的对象消息数据,封装发送消息方法:
import android.os.Bundle;
import android.os.Message; import java.io.Serializable; /**
* Created by Administrator on 2017/1/16.
*/ public class SendHandlerMsg { private static Message message; /**
* 建立bundle 向 fragment 中发送消息
*
* @param SerializableKey 系列化键值
* @param obj 消息内容,传入时必须先系列化对象,不然数据发送不出去,会导致堵塞异常
* 建立bundle 向 Activity 中发送消息
*
* @param SerializableKey 系列化键值
* @param obj 消息内容
*/
public static void ActivityHandlerMsg(final String SerializableKey, final Object obj) {
new Thread(new Runnable() {
@Override
public void run() {
/**
* myHandler 向CustomActivity中发送消息
* MyHandler myHandler = MyHandler.getInstance();这句
*必须放在线程内部,如果放在外面会导致getInstance(),Handler实类为空,Handler线程异常
*/
MyHandler myHandler = MyHandler.getInstance();
message = new Message();
Bundle bundle = new Bundle();
bundle.putSerializable(SerializableKey, (Serializable) obj);
message.setData(bundle);
myHandler.sendMessage(message);
}
}).start(); } }
下面用服务简单描述发送消息的过程:
package dfrz.me.android.pcfileshare.service; import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.util.Log; public class MyService extends Service { private MyBinder mybinder = new MyBinder();
// 得到Handler实类
MyHandler myHandler = MyHandler.getInstance(); public class MyBinder extends Binder {
/**
* 消息发送函数
* @param chatMsgEntity
*/
public void sendMsg(final ADInfo data) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
ADInfo adInfo = new ADInfo();
adInfo.setId("xxxxxx");
adInfo.setUrl("xxxxxxx");
.......
//发送消息到 Activity
SendHandlerMsg.ActivityHandlerMsg("ACT",adInfo);
}
}).start();
} /**
* 添加其他键值数据
* @param data
*/
public void sendMsg(final ADInfo data) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
ADInfo adInfo = new ADInfo();
adInfo.setId("xxxxxx");
adInfo.setUrl("xxxxxxx");
.......
//发送消息到 Activity
SendHandlerMsg.ActivityHandlerMsg("ACTIVITY",adInfo);
}
}).start();
} } public MyService() {
} @Override
public IBinder onBind(Intent intent) {
return mybinder;
} @Override
public void onCreate() { } }
Server
Activity代码展示:
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; import dfrz.me.android.pcfileshare.R;
import dfrz.me.android.pcfileshare.base.CustomActivity; public class MainActivity extends CustomActivity implements View.OnClickListener {
private Button sendMsg1, SendMsg2;
private TextView showMsg; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initView();
initData();
initOnClick();
} @Override
protected void initView() {
sendMsg1 = (Button) findViewById(R.id.sendMsg1);
sendMsg2 = (Button) findViewById(R.id.sendMsg2);
showMsg = (TextView) findViewById(R.id.showMsg);
} @Override
protected void initData() { } @Override
protected void initOnClick() {
sendMsg1.setOnClickListener(this);
sendMsg2.setOnClickListener(this);
back.setOnClickListener(this);
} @Override
public void recvMessageFormHandler(Bundle bundle) {
ADInfo adInfo = new ADInfo(); adInfo = (ADInfo) bundle.getSerializable("ACTI");
if (adInfo != null) {
showMsg.setText(adInfo.getUrl() + "");
}
// 这里可新new 一个实例接收消息
/**
* ChatMsg chatMsg = new ChatMsg(); chatMsg = (ChatMsg)
* bundle.getSerializable("CHAT"); 先判断chatMsg非空则接收到消息可更新UI
*/
Appinfo adInfo1 = new ADInfo();
adInfo1 = (ADInfo) bundle.getSerializable("ACTI");
if (adInfo1 != null) {
showMsg.setText(adInfo.getUrl() + "");
}
} @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sendMsg1:
{ ADInfo adInfo = new ADInfo();
adInfo.setId("xxxxxx");
adInfo.setUrl("xxxxxxx");
.......
binder.sendMsgA(adInfo);}
break;
case R.id.sendMsg2:{
ADInfo adInfo = new ADInfo();
adInfo.setId("1111111");
adInfo.setUrl("1111111111");
.......
binder.sendMsgB(adInfo);}
break;
}
} }
效果怎么样,这就不展示了,仅供参看,如有问题可提出来大家解决,有更好的建议还请各位大神多多指点,毕竟我还新手。thank you!
Android 消息传递之Bundle的使用——实现object对象传输(二)的更多相关文章
- Android 消息传递之Bundle的使用——实现object对象传输(一)
UI更新--消息处理massage 对于安卓内部消息得处理,实现对界面UI得更新操作,不能在线程中直接更新ui.至于为什么不能,在学习安卓开发的时候,在线程中操作会使程序崩溃. 为什么,可以看看诸多大 ...
- Android消息传递之基于RxJava实现一个EventBus - RxBus
前言: 上篇文章学习了Android事件总线管理开源框架EventBus,EventBus的出现大大降低了开发成本以及开发难度,今天我们就利用目前大红大紫的RxJava来实现一下类似EventBus事 ...
- Android消息传递之EventBus 3.0使用详解
前言: 前面两篇不仅学习了子线程与UI主线程之间的通信方式,也学习了如何实现组件之间通信,基于前面的知识我们今天来分析一下EventBus是如何管理事件总线的,EventBus到底是不是最佳方案?学习 ...
- Android消息传递之Handler消息机制
前言: 无论是现在所做的项目还是以前的项目中,都会遇见线程之间通信.组件之间通信,目前统一采用EventBus来做处理,在总结学习EventBus之前,觉得还是需要学习总结一下最初的实现方式,也算是不 ...
- Android学习笔记_46_Android的intent之间Object、List、List<Object>和全局变量数据的传递(Parcelable Serializable)
转http://blog.csdn.net/pku_android/article/details/7456305 一.传递List<String>和List<Integer> ...
- Android消息传递之组件间传递消息
前言: 上篇学习总结了Android通过Handler消息机制实现了工作线程与UI线程之间的通信,今天来学习一下如何实现组件之间的通信.本文依然是为学习EventBus做铺垫,有对比才能进步,今天主要 ...
- Android开发中Bundle用法包裹数据(转)
Android开发中Bundle用法包裹数据 Bundle的经典用法,包裹数据放入Intent中,目的在于传输数据. SDK 里是这样描述: A mapping from String values ...
- ReactNative生成android平台的bundle文件命令
ReactNative生成android平台的bundle文件命令 2016年11月03日 23:23:28 阅读数:4869 注:如果assets文件没有正确生成,需要手机创建或授权 网上的其它的很 ...
- Android消息传递之EventBus 3.0
Android消息传递之EventBus 3.0使用详解 http://www.cnblogs.com/whoislcj/p/5595714.html EventBus 3.0进阶:源码及其设计模式 ...
随机推荐
- 【【分享】深入浅出WPF全系列教程及源码
】
因为原书作者的一再要求,在此声明,本书中的部分内容引用了原书名为<深入浅出WPF>的部分内容,假设博文不能满足你现有的学习须要,能够购买正版图书! 本人10月份提出离职,可是交接非常慢,预 ...
- 异常:必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]
异常描述 异常:必须先将 ContentLength 字节写入请求流,然后再调用 [Begin] 解决方案 //解决异常:必须先将 ContentLength 字节写入请求流,然后再调用 [Begin ...
- 【转】android json解析及简单例子
JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...
- Value Object(值对象)如何使用 EF 进行正确映射
DDD 领域驱动设计-Value Object(值对象)如何使用 EF 进行正确映射 写在前面 首先,这篇博文是用博客园新发布的 MarkDown编辑器 编写的,这也是我第一次使用,语法也不是很熟悉, ...
- ASP.NET MVC项目里创建一个aspx视图
先从控制器里添加视图 视图引擎选"ASPX(C#)",使用布局或模板页不要选. 在Views\EAV目录里,生成的aspx是个单独的页面,没有代码文件,所以代码也要写在这个文件里. ...
- 存储过程的参数问题与C#中的调用
1. 带参数的存储过程 set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_select_gua] @num ...
- oauth与openid
转自http://desert3.iteye.com/blog/1701626 OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列 ...
- Python 用IMAP接收邮件
一.简介IMAP(Internet Message Access Protocol),这个协议与POP一样,也是从邮件服务器上下载邮件到本机,不过IMAP比POP的功能要更加强大些,IMAP除支持PO ...
- [转]iOS Tutorial – Dumping the Application Heap from Memory
Source:https://blog.netspi.com/ios-tutorial-dumping-the-application-heap-from-memory/ An essential ...
- 【编程范式】C语言1
最近在网易公开课上看斯坦福大学的<编程范式>,外国人讲课思路就是清晰,上了几节课,感觉难度确实比我们普通大学大很多,但是却很有趣,让人能边学边想. 范式编程,交换两个数,利用 void * ...