类似于淘口令的应用,打开app检测粘贴板内容,但是要求不能更改剪切板的内容,在自己的应用内只能检测一次,再者如果是自己应用内的淘口令,自己不能检测
插件链接:https://github.com/MonkZL/react-native-clipboard-command
插件用法
import { setCommand, useCommand } from 'react-native-clipboard-command';
export default function App() {
const [commandStr, setCommandStr] = React.useState('');
useCommand(
(command) => {
alert('复制过来的指令是: ' + command);
},
(reason) => {
alert(reason);
}
);
return (
<View style={styles.container}>
<TextInput
placeholder={'请输入口令'}
value={commandStr}
onChangeText={setCommandStr}
style={{
width: '50%',
height: 50,
borderWidth: 1,
paddingHorizontal: 10,
}}
/>
<TouchableOpacity
style={{
width: 100,
height: 100,
backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
}}
onPress={() => {
setCommand(commandStr);
alert('设置成功');
}}
>
<Text>设置口令</Text>
</TouchableOpacity>
</View>
);
}
android的插件实现方式 通过给ClipData
设置lable来判断是否是自己复制到粘贴板的内容
@ReactMethod
public void setCommand(String command) {
try {
ClipData clipdata = ClipData.newPlainText(getPackageName(), command);
ClipboardManager clipboard = getClipboardService();
clipboard.setPrimaryClip(clipdata);
} catch (Exception e) {
e.printStackTrace();
}
}
@ReactMethod
public void getCommand(Promise promise) {
try {
ClipboardManager clipboard = getClipboardService();
ClipData clipData = clipboard.getPrimaryClip();
if (clipData == null) {
promise.reject("0", "没有数据");
return;
}
CharSequence label = clipData.getDescription().getLabel();
if (TextUtils.equals(label, getPackageName())) {
promise.reject("1", "自己在应用内复制的指令");
return;
}
if (clipData.getItemCount() >= 1) {
ClipData.Item firstItem = clipboard.getPrimaryClip().getItemAt(0);
promise.resolve("" + firstItem.getText());
} else {
promise.reject("0", "没有数据");
}
} catch (Exception e) {
promise.reject("2", e.getMessage());
}
}
ios的插件实现方式 通过[systemBoard addItems:@[item]]
的方式设置标记
RCT_EXPORT_METHOD(setCommand:(NSString *)command)
{
//创建系统剪切板
UIPasteboard *systemBoard = [UIPasteboard generalPasteboard];
//将文本写入剪切板
systemBoard.string = command;
//给剪切板加入一条标记性的数据,只是为了检测剪切板的数据是否来自当前应用
NSDictionary<NSString *, id> *item = @{[[NSBundle mainBundle]bundleIdentifier]:command};
[systemBoard addItems:@[item]];
}
RCT_EXPORT_METHOD(getCommand:(RCTPromiseResolveBlock)resolve
reject:(__unused RCTPromiseRejectBlock)reject)
{
@try {
//创建系统剪切板
UIPasteboard *systemBoard = [UIPasteboard generalPasteboard];
if(!systemBoard.numberOfItems) {
reject(@"0",@"没有数据", nil);
return;
}
NSArray<NSDictionary<NSString *, id> *> *items = systemBoard.items;
long count = items.count;
for(int i=0; i < count; i++){
NSDictionary<NSString *, id> *item = [items objectAtIndex:i];
if([[item allKeys] containsObject:[[NSBundle mainBundle]bundleIdentifier]]){
reject(@"1",@"自己在应用内复制的指令", nil);
return;
}
}
resolve((systemBoard.string ? : @""));
} @catch (NSException *exception) {
reject(@"2",exception.reason, nil);
} @finally {
}
}
网友评论