phonegap(cordova) 入門 14---- 複製粘貼功能

大家都知道,js 是沒辦法直接操作本機剪切板的,那走插件唄,如下

android 

public class ClipboardPlugin extends CordovaPlugin {
	private static final String actionCopy = "copy";
    private static final String actionPaste = "paste";
	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		 ClipboardManager clipboard = (ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
		if (action.equals(actionCopy)) {
            try {
                String text = args.getString(0);
                ClipData clip = ClipData.newPlainText("Text", text);

                clipboard.setPrimaryClip(clip);

                callbackContext.success(text);

                return true;
            } catch (JSONException e) {
            	return false;
            } catch (Exception e) {
            	return false;
            }
        } else if (action.equals(actionPaste)) {
            if (!clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            	return false;
            }

            try {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                String text = item.getText().toString();

                if (text == null) text = "";

                callbackContext.success(text);

                return true;
            } catch (Exception e) {
            	return false;
            }
        }

        return false;
	}

	 
}
iOS

#import "CDVClipboard.h"
@implementation CDVClipboard
@synthesize callbackID;
- (void)copy:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSString     *text       = [command.arguments objectAtIndex:0];
        
        [pasteboard setValue:text forPasteboardType:@"public.text"];
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:text];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)paste:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSString     *text       = [pasteboard valueForPasteboardType:@"public.text"];
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:text];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}
@end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章