本文主要是介绍cocosCreator获取手机剪切板内容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近游戏中需要加上复制粘贴的功能,这个时候就涉及到安卓原生层的东西。步骤如下:
公开文章地址,见个人博客
复制功能
ts代码
调用代码,在需要复制的地方调用即可。
public static copyToClipBoard(str) {if (sys.platform == sys.Platform.ANDROID) {PlatformMgr.callNativeFn("copyToClipboard", str);}}
static async callNativeFn(funcName: string, jsonMsg?: string): Promise<{ msg: string, isSucc: boolean }> {if (sys.platform != sys.Platform.ANDROID) // TODO: web 暂时只支持 Android 调用returnlet fn = PlatformMgr.Ins._platformIns[funcName]if (typeof (fn) == "function") { // 支持重写方法return await fn(funcName, jsonMsg)} else {return await PlatformMgr.Ins._platformIns.callNativeFn(funcName, jsonMsg)}}
import { NativeMgr } from "../../module/native/NativeMgr";export class PlatformBase {// 最终调用 natvie 接口async callNativeFn(funcName: string, jsonMsg?: string) {return new Promise<{ msg: string, isSucc: boolean }>((resolve) => {NativeMgr.Ins.callNativeFunc((msg: string, isSucc: boolean) => {resolve({ msg: msg, isSucc: isSucc })}, funcName, jsonMsg)})}
}
java代码
放在你自己的逻辑中,放在AppActivity.java
中即可。前面需要import
相关的库文件
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
调用代码:
public static void copyToClipboard(String textToCopy) {// 获取剪贴板管理器ClipboardManager clipboardManager = (ClipboardManager) getActivity().getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);// 创建 ClipData 对象ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);// 将 ClipData 设置到剪贴板clipboardManager.setPrimaryClip(clipData);try {JSONObject jsonobj = new JSONObject();jsonobj.put("type", "copyText");jsonobj.put("code", "1");Log.d("copyToClipboard", jsonobj.toString());String str = String.format("NativeAndroid.javaCallback(\'%s\')", jsonobj.toString());
// CocosJavascriptJavaBridge.evalString(str);callJsGlobalFunc(str);} catch (Exception e) {}}
获取剪切板内容
ts代码
public static copyToClipBoard(str) {if (sys.platform == sys.Platform.ANDROID) {let android = new AndroidNative();android.getText("getText");}}
export class AndroidNative implements INativeCaller {getText(funcName: string, jsonMsg: string = "{}") { let getText = native.reflection.callStaticMethod(this._activityName, funcName, "()Ljava/lang/String;");console.log("剪切板内容")}
}
java代码
public static String getText(){ClipboardManager clipboard = (ClipboardManager) getActivity().getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);ClipData clip = clipboard.getPrimaryClip();if (clip != null && clip.getItemCount() > 0) {Log.d("剪切板内容 = ",clip.getItemAt(0).coerceToText(getActivity().getApplicationContext()).toString());return clip.getItemAt(0).coerceToText(getActivity().getApplicationContext()).toString();}return null;}
这篇关于cocosCreator获取手机剪切板内容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!