zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【HarmonyOS】【JAVA UI】 HarmonyOS如何集成华为分享

JAVA集成华为UI 如何 分享 HarmonyOS
2023-09-11 14:17:16 时间

 参考资料

服务接入华为分享开发指导

代码集成

1.集成IDL接口,用于建立分享方与华为分享的交互通道,完成后续服务分享过程。

在“java”目录同级目录创建“idl”接口目录(可手动添加或通过DevEco Studio创建):com/huawei/hwshare/third(固定路径),然后创建名为IHwShareCallback.idl和IHwShareService.idl的IDL文件。

IHwShareCallback.idl :
interface com.huawei.hwshare.third.IHwShareCallback {
    [oneway] void notifyState([in] int state);
}

IHwShareService.idl :
sequenceable ohos.interwork.utils.PacMapEx;
interface com.huawei.hwshare.third.IHwShareCallback;

interface com.huawei.hwshare.third.IHwShareService {
    int startAuth([in] String appId, [in] IHwShareCallback callback);
    int shareFaInfo([in] PacMapEx pacMapEx);
}

2.创建ShareFaManager类,用于管理分享方与华为分享的连接通道和数据交互。

import com.huawei.hwshare.third.HwShareCallbackStub;
import com.huawei.hwshare.third.HwShareServiceProxy;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.bundle.ElementName;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.interwork.utils.PacMapEx;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class ShareFaManager {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, "ShareFa");

    private static final String LOG_FORMAT = "%{public}s: %{public}s";

    public static final String HM_FA_ICON = "ohos_fa_icon";

    public static final String HM_FA_NAME = "ohos_fa_name";

    public static final String HM_ABILITY_NAME = "ohos_ability_name";

    public static final String HM_BUNDLE_NAME = "ohos_bundle_name";

    public static final String SHARING_FA_TYPE = "sharing_fa_type";

    public static final String SHARING_THUMB_DATA = "sharing_fa_thumb_data";

    public static final String SHARING_CONTENT_INFO = "sharing_fa_content_info";

    public static final String SHARING_EXTRA_INFO = "sharing_fa_extra_info";

    private static final String TAG = "ShareHmFaManager";

    private static final String SHARE_PKG_NAME = "com.huawei.android.instantshare";

    private static final String SHARE_ACTION = "com.huawei.instantshare.action.THIRD_SHARE";

    private static final long UNBIND_TIME = 20*1000L;

    private Context mContext;

    private String mAppId;

    private PacMapEx mSharePacMap;

    private static ShareFaManager sSingleInstance;

    private HwShareServiceProxy mShareService;

    private boolean mHasPermission = false;

    private EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());

    private final IAbilityConnection mConnection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
        HiLog.error(LABEL_LOG, LOG_FORMAT, TAG, "onAbilityConnectDone success.");
        mHandler.postTask(()->{
            mShareService = new HwShareServiceProxy(iRemoteObject);
                try {
                    mShareService.startAuth(mAppId, mFaCallback);
                } catch (RemoteException e) {
                    HiLog.error(LABEL_LOG, LOG_FORMAT, TAG, "startAuth error.");
                }
                });
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {
                HiLog.info(LABEL_LOG, LOG_FORMAT, TAG, "onAbilityDisconnectDone.");
                mHandler.postTask(()->{
                    mShareService = null;
                    mHasPermission = false;
                    });
            }
    };

    private Runnable mTask = () -> {
        if (mContext != null && mShareService != null) {
            mContext.disconnectAbility(mConnection);
            mHasPermission = false;
            mShareService = null;
        }
    };

    private final HwShareCallbackStub mFaCallback = new HwShareCallbackStub("HwShareCallbackStub") {
        @Override
        public void notifyState(int state) throws RemoteException {
            mHandler.postTask(()->{
                HiLog.info(LABEL_LOG, LOG_FORMAT, TAG, "notifyState: " + state);
                if (state == 0) {
                    mHasPermission = true;
                    if (mSharePacMap != null) {
                        shareFaInfo();
                    }
                }
            });
        }
    };

    /**
     * 单例模式获取ShareFaManager的实例对象
     *
     * @param context 程序Context
     * @return ShareFaManager实例对象
     */
    public static synchronized ShareFaManager getInstance(Context context) {
        if (sSingleInstance == null && context != null) {
            sSingleInstance = new ShareFaManager(context.getApplicationContext());
        }
        return sSingleInstance;
    }

    private ShareFaManager(Context context) {
        mContext = context;
    }

    private void shareFaInfo() {
        if (mShareService == null) {
            return;
        }
        if (mHasPermission) {
            HiLog.info(LABEL_LOG, LOG_FORMAT, TAG, "start shareFaInfo.");
            try {
                mShareService.shareFaInfo(mSharePacMap);
                mSharePacMap = null;
            } catch (RemoteException e) {
                HiLog.error(LABEL_LOG, LOG_FORMAT, TAG, "shareFaInfo error.");
            }
        }
        // 不使用时断开
        mHandler.postTask(mTask, UNBIND_TIME);
    }

    /**
     * 用于分享服务
     *
     * @param appId 开发者联盟网站创建原子化服务时生成的appid
     * @param pacMap 服务信息载体
     */
    public void shareFaInfo(String appId, PacMapEx pacMap) {
        if (mContext == null) {
            return;
        }
        mAppId = appId;
        mSharePacMap = pacMap;
        mHandler.removeTask(mTask);
        shareFaInfo();
        bindShareService();
    }

    private void bindShareService() {
        if (mShareService != null) {
            return;
        }
        HiLog.error(LABEL_LOG, LOG_FORMAT, TAG, "start bindShareService.");
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName(SHARE_PKG_NAME)
            .withAction(SHARE_ACTION)
            .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
            .build();
        intent.setOperation(operation);
        mContext.connectAbility(intent, mConnection);
    }
}

效果如图所示

cke_3007.png

代码实现

xml代码绘画一个text按钮,代码如下

<?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:alignment="center"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_huaweiShare"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:background_element="$graphic:background_ability_main"
        ohos:layout_alignment="horizontal_center"
        ohos:text="华为分享"
        ohos:text_size="40vp"
        />

</DirectionalLayout>

java 代码给按钮实现点击事件,需要注意的必选参数,代码如下

package com.harmony.alliance.myapplication.slice;

import com.harmony.alliance.myapplication.MainAbility;
import com.harmony.alliance.myapplication.ResourceTable;
import com.harmony.alliance.myapplication.ShareFaManager;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.global.resource.Resource;
import ohos.interwork.utils.PacMapEx;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        findComponentById(ResourceTable.Id_text_huaweiShare).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    PacMapEx pacMap = new PacMapEx();
                    //todo 必选参数  分享的服务的bundleName
                    pacMap.putObjectValue(ShareFaManager.HM_BUNDLE_NAME, getBundleName());
                    //todo 分享的服务的Ability类名,最大长度1024,必选参数。
                    pacMap.putObjectValue(ShareFaManager.HM_ABILITY_NAME, MainAbility.class.getName());
                    //todo   卡片展示的服务介绍信息,最大长度1024,必选参数。
                    pacMap.putObjectValue(ShareFaManager.SHARING_CONTENT_INFO, "卡片展示的服务介绍信息");
                    Resource resource = getResourceManager().getRawFileEntry("resources/base/media/icon.png").openRawFile();
                    int size = resource.available();
                    byte[] buffer = new byte[size];
                    resource.read(buffer);
                    resource.close();
                    //todo   卡片展示服务介绍图片,最大长度153600,必选参数。
                pacMap.putObjectValue(ShareFaManager.SHARING_THUMB_DATA, buffer);
                // 携带的额外信息,可传递到被拉起的服务界面 ,最大长度10240,非必选参数。
                    pacMap.putObjectValue(ShareFaManager.SHARING_EXTRA_INFO, "分享的参数");
                    //服务图标,如果不传递此参数,取分享方默认服务图标,最大长度32768,非必选参数。
                    pacMap.putObjectValue(ShareFaManager.HM_FA_ICON, buffer);
                    //卡片展示的服务名称,最大长度1024,非必选参数。如果不传递此参数,取分享方默认服务名称。
                    pacMap.putObjectValue(ShareFaManager.HM_FA_NAME, "FAShareDemo");
                    // todo 第一个参数为appid,在华为AGC创建原子化服务时自动生成。
                    ShareFaManager.getInstance(MainAbilitySlice.this).shareFaInfo("自己的项目的appid", pacMap);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

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

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

运行效果

cke_11873.png

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh