cocos2dx项目复制文字到手机粘贴板

有的游戏中会提示添加官方微信或者关注公众号,为了方便玩家操作,就会有一个复制到粘贴板的功能。废话不多说了,直接上代码吧。

c++代码如下:

void WxApiInterFace::CopyStringToClipBoard(const char* roomIdStr)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo minfo;
log("jni CopyRoomIDAndroid is %s", roomIdStr);
bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/lua/AppActivity", "CopyStringToClipBoard", "(Ljava/lang/String;)I");


if (!isHave)
{
log("jni CopyStringToClipBoard is null");
}
else
{
jstring jroomIdStr = minfo.env->NewStringUTF(roomIdStr);
jint copyResult = (jint)minfo.env->CallStaticIntMethod(minfo.classID, minfo.methodID, jroomIdStr);
}
#endif


#if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
int copyResult = IOSPlatform::GetInstance().copyOC(roomIdStr);
#endif

}

java中的代码如下:

    //复制房间ID
    public static int CopyStringToClipBoard(final String copyString){
    try
         {
             Runnable runnable = new Runnable() {
                 public void run() {               
                     ClipboardManager clipboard = (ClipboardManager) instance.getSystemService(Context.CLIPBOARD_SERVICE);
                     android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", copyString);
                     clipboard.setPrimaryClip(clip);
                 }
             };
             //getSystemService运行所在线程必须执行过Looper.prepare()
             //否则会出现Can't create handler inside thread that has not called Looper.prepare()
             ((Cocos2dxActivity)instance).runOnUiThread(runnable);
  
         }catch(Exception e){
             e.printStackTrace();
             return -1;
         }
         return 0;

    }

这样就好了,只需要简单的调用一下c++函数就完成了复制粘贴板功能了,至于想复制啥,就随意了。

另外把ios的方法也加上去:

//拷贝到系统剪切板
int IOSPlatform::copyOC(const char* roomIdStr)
{
    //把char*转换成OC的NSString  
    NSString *nsMessage= [[NSString alloc] initWithCString:roomIdStr encoding:NSUTF8StringEncoding];  
      
    //获得iOS的剪切板  
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];  
      
    //改变剪切板的内容  
    pasteboard.string = nsMessage;  
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值