探索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

相关文章

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

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

Java中的xxl-job调度器线程池工作机制

《Java中的xxl-job调度器线程池工作机制》xxl-job通过快慢线程池分离短时与长时任务,动态降级超时任务至慢池,结合异步触发和资源隔离机制,提升高频调度的性能与稳定性,支撑高并发场景下的可靠... 目录⚙️ 一、调度器线程池的核心设计 二、线程池的工作流程 三、线程池配置参数与优化 四、总结:线程

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

MySQL中的锁机制详解之全局锁,表级锁,行级锁

《MySQL中的锁机制详解之全局锁,表级锁,行级锁》MySQL锁机制通过全局、表级、行级锁控制并发,保障数据一致性与隔离性,全局锁适用于全库备份,表级锁适合读多写少场景,行级锁(InnoDB)实现高并... 目录一、锁机制基础:从并发问题到锁分类1.1 并发访问的三大问题1.2 锁的核心作用1.3 锁粒度分