探索Android中的Parcel机制(下)

2024-01-07 10:08
文章标签 android 探索 机制 parcel

本文主要是介绍探索Android中的Parcel机制(下),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

http://blog.csdn.net/caowenbin/article/details/6532238


  上一篇中我们透过源码看到了Parcel背后的机制,本质上把它当成一个Serialize就可以了,只是它是在内存中完成的序列化和反序列化,利用的是连续的内存空间,因此会更加高效。

         我们接下来要说的是Parcel类如何应用。就应用程序而言,最常见使用Parcel类的场景就是在Activity间传递数据。没错,在Activity间使用Intent传递数据的时候,可以通过Parcelable机制传递复杂的对象。

         在下面的程序中,MyColor用于保存一个颜色值,MainActivity在用户点击屏幕时将MyColor对象设成红色,传递到SubActivity中,此时SubActivity的TextView显示为红色的背景;当点击SubActivity时,将颜色值改为绿色,返回MainActivity,期望的是MainActivity的TextView显示绿色背景。

         来看一下MyColor类的实现代码:

    package com.wenbin.test;  import android.graphics.Color;  import android.os.Parcel;  import android.os.Parcelable;  /** * @author 曹文斌 * http://blog.csdn.net/caowenbin * */  public class MyColor implements Parcelable {  private int color=Color.BLACK;  MyColor(){  color=Color.BLACK;  }  MyColor(Parcel in){  color=in.readInt();  }  public int getColor(){  return color;  }  public void setColor(int color){  this.color=color;  }  @Override  public int describeContents() {  return 0;  }  @Override  public void writeToParcel(Parcel dest, int flags) {  dest.writeInt(color);  }  public static final Parcelable.Creator<MyColor> CREATOR  = new Parcelable.Creator<MyColor>() {  public MyColor createFromParcel(Parcel in) {  return new MyColor(in);  }  public MyColor[] newArray(int size) {  return new MyColor[size];  }  };  }  

 

         该类实现了Parcelable接口,提供了默认的构造函数,同时也提供了可从Parcel对象开始的构造函数,另外还实现了一个static的构造器用于构造对象和数组。代码很简单,不一一解释了。

         再看MainActivity的代码:

    package com.wenbin.test;  import android.app.Activity;  import android.content.Intent;  import android.graphics.Color;  import android.os.Bundle;  import android.view.MotionEvent;  /** * @author 曹文斌 * http://blog.csdn.net/caowenbin * */  public class MainActivity extends Activity {  private final int SUB_ACTIVITY=0;  private MyColor color=new MyColor();  @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  }  @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  super.onActivityResult(requestCode, resultCode, data);  if (requestCode==SUB_ACTIVITY){  if (resultCode==RESULT_OK){  if (data.hasExtra("MyColor")){  color=data.getParcelableExtra("MyColor");  //Notice  findViewById(R.id.text).setBackgroundColor(color.getColor());  }  }  }  }  @Override  public boolean onTouchEvent(MotionEvent event){  if (event.getAction()==MotionEvent.ACTION_UP){  Intent intent=new Intent();  intent.setClass(this, SubActivity.class);  color.setColor(Color.RED);  intent.putExtra("MyColor", color);  startActivityForResult(intent,SUB_ACTIVITY);      }  return super.onTouchEvent(event);  }  }  

 

        下面是SubActivity的代码:

 

    package com.wenbin.test;  import android.app.Activity;  import android.content.Intent;  import android.graphics.Color;  import android.os.Bundle;  import android.view.MotionEvent;  import android.widget.TextView;  /** * @author 曹文斌 * http://blog.csdn.net/caowenbin * */  public class SubActivity extends Activity {  private MyColor color;  @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  ((TextView)findViewById(R.id.text)).setText("SubActivity");  Intent intent=getIntent();  if (intent!=null){  if (intent.hasExtra("MyColor")){  color=intent.getParcelableExtra("MyColor");  findViewById(R.id.text).setBackgroundColor(color.getColor());  }  }  }  @Override  public boolean onTouchEvent(MotionEvent event){  if (event.getAction()==MotionEvent.ACTION_UP){  Intent intent=new Intent();  if (color!=null){  color.setColor(Color.GREEN);  intent.putExtra("MyColor", color);  }  setResult(RESULT_OK,intent);  finish();  }  return super.onTouchEvent(event);  }  }  

 

        下面是main.xml的代码:

    <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  >  <TextView    android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="@string/hello"  android:id="@+id/text"  />  </LinearLayout>  

 

        注意的是在MainActivity的onActivityResult()中,有一句color=data.getParcelableExtra("MyColor"),这说明的是反序列化后是一个新的MyColor对象,因此要想使用这个对象,我们做了这个赋值语句。

         记得在上一篇《探索Android中的Parcel机制(上)》中提到,如果数据本身是IBinder类型,那么反序列化的结果就是原对象,而不是新建的对象,很显然,如果是这样的话,在反序列化后在MainActivity中就不再需要color=data.getParcelableExtra("MyColor")这句了。因此,换一种MyColor的实现方法,令其中的int color成员变量使用IBinder类型的成员变量来表示。

         新建一个BinderData类继承自Binder,代码如下:

 

    package com.wenbin.test;  import android.os.Binder;  /** * @author 曹文斌 * http://blog.csdn.net/caowenbin * */  public class BinderData extends Binder {  public int color;  }  

  

       修改MyColor的代码如下:


    package com.wenbin.test;  import android.graphics.Color;  import android.os.Parcel;  import android.os.Parcelable;  /** * @author 曹文斌 * http://blog.csdn.net/caowenbin * */  public class MyColor implements Parcelable {  private BinderData data=new BinderData();  MyColor(){  data.color=Color.BLACK;  }  MyColor(Parcel in){  data=(BinderData) in.readValue(BinderData.class.getClassLoader());  }  public int getColor(){  return data.color;  }  public void setColor(int color){  data.color=color;  }  @Override  public int describeContents() {  return 0;  }  @Override  public void writeToParcel(Parcel dest, int flags) {  dest.writeValue(data);  }  public static final Parcelable.Creator<MyColor> CREATOR  = new Parcelable.Creator<MyColor>() {  public MyColor createFromParcel(Parcel in) {  return new MyColor(in);  }  public MyColor[] newArray(int size) {  return new MyColor[size];  }  };  }  

         去掉MainActivity的onActivityResult()中的color=data.getParcelableExtra("MyColor")一句,变成:

 

    @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  super.onActivityResult(requestCode, resultCode, data);  if (requestCode==SUB_ACTIVITY){  if (resultCode==RESULT_OK){  if (data.hasExtra("MyColor")){  findViewById(R.id.text).setBackgroundColor(color.getColor());  }  }  }  }  

         再次运行程序,结果符合预期。

 

         以上就是Parcel在应用程序中的使用方法,与Serialize还是挺相似的,详细的资料当然还是要参考Android SDK的开发文档了。

——欢迎转载,请注明出处 http://blog.csdn.net/caowenbin ——



这篇关于探索Android中的Parcel机制(下)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/579561

相关文章

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

基于Redis自动过期的流处理暂停机制

《基于Redis自动过期的流处理暂停机制》基于Redis自动过期的流处理暂停机制是一种高效、可靠且易于实现的解决方案,防止延时过大的数据影响实时处理自动恢复处理,以避免积压的数据影响实时性,下面就来详... 目录核心思路代码实现1. 初始化Redis连接和键前缀2. 接收数据时检查暂停状态3. 检测到延时过

Redis中哨兵机制和集群的区别及说明

《Redis中哨兵机制和集群的区别及说明》Redis哨兵通过主从复制实现高可用,适用于中小规模数据;集群采用分布式分片,支持动态扩展,适合大规模数据,哨兵管理简单但扩展性弱,集群性能更强但架构复杂,根... 目录一、架构设计与节点角色1. 哨兵机制(Sentinel)2. 集群(Cluster)二、数据分片

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

深入理解go中interface机制

《深入理解go中interface机制》本文主要介绍了深入理解go中interface机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前言interface使用类型判断总结前言go的interface是一组method的集合,不

C# async await 异步编程实现机制详解

《C#asyncawait异步编程实现机制详解》async/await是C#5.0引入的语法糖,它基于**状态机(StateMachine)**模式实现,将异步方法转换为编译器生成的状态机类,本... 目录一、async/await 异步编程实现机制1.1 核心概念1.2 编译器转换过程1.3 关键组件解析

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

Go语言并发之通知退出机制的实现

《Go语言并发之通知退出机制的实现》本文主要介绍了Go语言并发之通知退出机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、通知退出机制1.1 进程/main函数退出1.2 通过channel退出1.3 通过cont