一呢燥、在基類Help.cpp文件中加入:
int copyToClipboard(const std::string& paras) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
????????JniMethodInfo minfo;
????????if (JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity","copyToClipboard", "(Ljava/lang/String;)I"))
????????{
????????????????jstring jstr = minfo.env->NewStringUTF(paras.c_str());
????????????????int code = minfo.env->CallStaticIntMethod(minfo.classID, minfo.methodID, jstr);
????????????????return code;
????????}
#endif
????????return -1;
}
二悼潭、在Help.h中加入:
//復(fù)制到剪貼板
int copyToClipboard(const std::string& paras);
三蹦渣、在需要調(diào)用的地方直接調(diào)用猾编,比如按下一個按鈕復(fù)制:
void Spread::buttonEventWithCopy(cocos2d::Ref *ref, cocos2d::ui::Widget::TouchEventType type)
{
????????if (type == cocos2d::ui::Widget::TouchEventType::ENDED)
????????{
????????????????copyToClipboard("copytext");
????????}
}
四夷恍、編輯安卓包下org/cocos2dx/cpp/AppActivity.java文件
public class AppActivityextends Cocos2dxActivity {
????????static AppActivitysgsActivity;
????????protected void onCreate(Bundle savedInstanceState) {
????????????????super.onCreate(savedInstanceState);
????????????????sgsActivity =this;
????????}
????????//參數(shù)要加final關(guān)鍵字蚓峦,否則內(nèi)部類不能訪問
????????static public int copyToClipboard(final String text) {
????????????????final Context context =sgsActivity;//參數(shù)要加final關(guān)鍵字卵迂,否則內(nèi)部類不能訪問
? ? ? ? ????????try {
????????????????????????Log.d("cocos2dx","copyToClipboard " + text);
????????????????????????Runnable runnable =new Runnable() {
????????????????????????????????public void run() {
????????????????????????????????????????android.content.ClipboardManager clipboard = ????????????????????????????????(android.content.ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
????????????????????????????????????????android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text",text);
????????????????????????????????????????clipboard.setPrimaryClip(clip);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
????????????????};
????????????????//getSystemService運(yùn)行所在線程必須執(zhí)行過Looper.prepare()
????????????????//否則會出現(xiàn)Can't create handler inside thread that has not called Looper.prepare()
????????????????sgsActivity.runOnUiThread(runnable);
????????????????}catch (Exception e) {
????????????????????????Log.d("cocos2dx","copyToClipboard error");
????????????????????????e.printStackTrace();
????????????????????????return -1;
????????????????}
????????????????return 0;
????????}
}