Ability之間或者程式間資料傳遞之物件(Sequenceable序列化)

HarmonyOS技術社群發表於2021-02-26

鴻蒙入門指南,小白速來!0基礎學習路線分享,高效學習方法,重點答疑解惑--->【課程入口】

這兩天51cto上的一個粉絲朋友問了我一個問題,Ability之間使用Sequenceable序列化傳遞資料,如何傳遞Uri型別資料?網上確實也沒有介紹這個使用的demo,為了幫他解決問題,自己幫他寫了一個demo,順手釋出一篇部落格和原始碼。

seralizable是在java api中的類,用它也可以實現序列化,而在android中也有一個類使物件序列化,那就是parcelable,而在HarmonyOS中用Sequenceable來進行序列化。

那麼它們之間有什麼區別呢?

seralizable:序列化到本地,是一個持久化的操作,效率慢一點

parcelable:只存在於記憶體,程式結束,序列化後的物件就不存在了。效率快一點
Sequenceable:等同parcelable在Android中的作用。

 

下面我編寫兩個AbilitySlice之間互相跳轉來傳遞資料

MainAbilitySlice對應的佈局檔案程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_helloworld"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:background_element="$graphic:background_ability_main"
        ohos:layout_alignment="horizontal_center"
        ohos:text="Hello World"
        ohos:text_size="50"
    />

</DirectionalLayout>

就是系統自動生成的helloworld,我偷懶就沒修改了,核心不在這裡。

再建立一個TestSlice,佈局程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_helloworld"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:background_element="$graphic:background_ability_main"
        ohos:layout_alignment="horizontal_center"
        ohos:text="TEST"
        ohos:text_size="50"
    />

</DirectionalLayout>

為了要在兩個Slice中間傳遞一個序列化物件資料,需要先建立一個實體類,並且實現Sequenceable介面,這裡才是整個的核心程式碼,如下:

package com.xdw.sequencedemo;

import ohos.utils.Parcel;
import ohos.utils.Sequenceable;
import ohos.utils.net.Uri;

/**
 * Created by 夏德旺 on 2021/2/26 10:39
 */
public class Student implements Sequenceable {
    private int number;

    private String name;

    private Uri uri;


    public Student() {
    }

    public Student(int number, String name, Uri uri) {
        this.number = number;
        this.name = name;
        this.uri = uri;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Uri getUri() {
        return uri;
    }

    public void setUri(Uri uri) {
        this.uri = uri;
    }

    //上面是傳統的實體類的建構函式和getter、setter
    //下面是序列化的核心
    //向包裹中寫入資料,包裹可以理解為一塊記憶體區
    public boolean marshalling(Parcel out) {
        out.writeSequenceable(uri); //注意Uri型別的寫法和普通資料型別有所不同
        return out.writeInt(number) && out.writeString(name);
    }

    //從包裹中讀取資料
    public boolean unmarshalling(Parcel in) {
        this.number = in.readInt();
        this.name = in.readString();
        return in.readSequenceable(uri);    //注意Uri型別的寫法和普通資料型別有所不同
    }

    //序列化物件的內部構造器,必須實現
    public static final Sequenceable.Producer
            PRODUCER = new Sequenceable.Producer
            () {
        public Student createFromParcel(Parcel in) {    //從包裹中獲取資料構造物件
            // Initialize an instance first, then do customized unmarshlling.
            Student instance = new Student();
            instance.unmarshalling(in);
            return instance;
        }   //必須實現Producer
    };
}

 

下面編寫MainAbilitySlice的程式碼,給Text控制元件新增一個點選事件來跳轉頁面並且傳遞一個student引數

package com.xdw.sequencedemo.slice;

import com.xdw.sequencedemo.ResourceTable;
import com.xdw.sequencedemo.Student;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.net.Uri;

public class MainAbilitySlice extends AbilitySlice {
    private Text text;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        text = (Text)findComponentById(ResourceTable.Id_text_helloworld);
        text.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                Student student = new Student();
                student.setNumber(1);
                student.setName("夏德旺");
                Uri uri = Uri.parse("http://www.xiadewang.com:8080/login?username=xdw&password=123");
                String scheme = uri.getScheme();
                //new ToastDialog(getContext()).setText("scheme="+scheme).show();
                student.setUri(uri);
                intent1.setParam("student",student);
                present(new TestSlice(),intent1);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

 

編寫TestSlice的程式碼接收傳遞過來的student引數,並且通過toast展示

package com.xdw.sequencedemo.slice;

import com.xdw.sequencedemo.ResourceTable;
import com.xdw.sequencedemo.Student;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.net.Uri;

/**
 * Created by 夏德旺 on 2021/2/26 10:39
 */
public class TestSlice  extends AbilitySlice {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_test);
        if(intent!=null){
            Student student = intent.getSequenceableParam("student");
            String name = student.getName();
            Uri uri = student.getUri();
            //new ToastDialog(getContext()).setText("name="+name).show();
            new ToastDialog(getContext()).setText("scheme="+uri.getScheme()).show();
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

 

到此,程式碼編寫完成,下面是執行測試圖

Ability之間或者程式間資料傳遞之物件(Sequenceable序列化)

這裡也順便完美解決了之前51cto上的粉絲朋友問我的Sequenceable物件無法讀取Uri資料的問題。

下載demo原始碼

作者:軟通夏德旺

想了解更多內容,請訪問51CTO和華為合作共建的鴻蒙社群:https://harmonyos.51cto.com

相關文章