当前位置: 代码迷 >> 综合 >> Unity 复制粘贴 调用安卓代码 获取安卓剪切板
  详细解决方案

Unity 复制粘贴 调用安卓代码 获取安卓剪切板

热度:97   发布时间:2023-11-05 17:38:39.0

欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群


安卓端 代码

package com.yyx.anq;/*** Created by zhy on 2018/7/29.*/import android.app.Fragment;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ClipData;import com.unity3d.player.UnityPlayer;
//import com.unity3d.player.UnityPlayer;
//import com.unity3d.player.UnityPlayerActivity;public class ReplicationTool extends Fragment //注意,这里继承的是Fragment
{private static final String TAG = "Plugin";private static ReplicationTool Instance = null;private String gameObjectName;public static ReplicationTool GetInstance(String gameObject){if(Instance == null){Instance = new ReplicationTool();Instance.gameObjectName = gameObject;UnityPlayer.currentActivity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();}return Instance;}//拷贝String到剪贴板public String onClickCopy(String str) {//获取剪贴板管理器:ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);// 创建普通字符型ClipDataClipData mClipData = ClipData.newPlainText("Label", str); //Label是任意文字标签// 将ClipData内容放到系统剪贴板里。cm.setPrimaryClip(mClipData);return  "已复制内容到剪切板";}//粘贴public String onClickPaste(){ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);String result = "";ClipData clipData = cm.getPrimaryClip();//result = cm.toString(); //ClipData{ text/plain "Label"{T:"str"}}; //取出的是ClipData//result = cm.getText().toString(); //"str" //方法deprecatedClipData.Item item = clipData.getItemAt(0); //这里获取第一条,也可以用遍历获取任意条CharSequence charSequence = item.coerceToText(getActivity().getApplicationContext());result = charSequence.toString();return result;}}

Unity端代码

  protected override void Awake(){base.Awake();jc = new AndroidJavaClass("com.yyx.anq.ReplicationTool"); //和java代码包名统一}public void OnClickCopy(string str){var jo = jc.CallStatic<AndroidJavaObject>("GetInstance", gameObject.name);var a = jo.Call<string>("onClickCopy", str);GameTool.MakeToast(a);Debug.Log(a);}

亲测可用


欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群

  相关解决方案