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

欢迎加入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);
        // 创建普通字符型ClipData
        ClipData 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" //方法deprecated
        ClipData.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("GetInstance", gameObject.name);
        var a = jo.Call("onClickCopy", str);

        GameTool.MakeToast(a);
        Debug.Log(a);
    }

亲测可用


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

qq扫描二维码加群

你可能感兴趣的:(Unity 复制粘贴 调用安卓代码 获取安卓剪切板)