最近游戏中需要加上复制粘贴的功能,这个时候就涉及到安卓原生层的东西。步骤如下:
复制功能
ts代码
调用代码,在需要复制的地方调用即可。
1 2 3 4 5
| public static copyToClipBoard(str) { if (sys.platform == sys.Platform.ANDROID) { PlatformMgr.callNativeFn("copyToClipboard", str); } }
|
1 2 3 4 5 6 7 8 9 10 11
| static async callNativeFn(funcName: string, jsonMsg?: string): Promise<{ msg: string, isSucc: boolean }> { if (sys.platform != sys.Platform.ANDROID) return
let fn = PlatformMgr.Ins._platformIns[funcName] if (typeof (fn) == "function") { return await fn(funcName, jsonMsg) } else { return await PlatformMgr.Ins._platformIns.callNativeFn(funcName, jsonMsg) } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { NativeMgr } from "../../module/native/NativeMgr";
export class PlatformBase {
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
相关的库文件
1 2 3
| import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context;
|
调用代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public static void copyToClipboard(String textToCopy) { ClipboardManager clipboardManager = (ClipboardManager) getActivity().getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);
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());
callJsGlobalFunc(str); } catch (Exception e) { } }
|
获取剪切板内容
ts代码
1 2 3 4 5 6
| public static copyToClipBoard(str) { if (sys.platform == sys.Platform.ANDROID) { let android = new AndroidNative(); android.getText("getText"); } }
|
1 2 3 4 5 6
| export class AndroidNative implements INativeCaller { getText(funcName: string, jsonMsg: string = "{}") { let getText = native.reflection.callStaticMethod(this._activityName, funcName, "()Ljava/lang/String;"); console.log("剪切板内容") } }
|
java代码
1 2 3 4 5 6 7 8 9
| 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; }
|