在OS X Java应用程序中处理自定义URL方案
我们基于Java的应用程序的Info.plist
包含以下条目:
... CFBundleURLTypes CFBundleURLName myApp handler CFBundleURLSchemes myapp ...
它应该处理像myapp://foobar/bazz
这样的URL。 打开应用程序工作正常,但应用程序应如何获取单击的URL?
对于Objective C,可以在此处找到答案: 当通过注册的URL方案启动OS X应用程序时,如何访问完整的URL?
Java的解决方案是将ObjC代码重写为普通的C,然后在org.eclipse.swt.internal.cocoa.*
下的一组类的帮助下将其转换为Java。
作为ObjC-to-C转换的参考,我们需要Apple的Objective-C运行时参考 。
普通C版
首先,让我们翻译
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:targetObject andSelector:@selector(handleAppleEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
在普通C中调用ObjC函数,我们使用objc_msgSend()
。 此外, @selector(method_footprint)
由sel_registerName("method_footprint")
替换,并使用objc_getClass()
查找类。 类型id
和SEL
等效于指针(例如void *)或全尺寸int(即与void *相同的大小)。
结果:
// id mgr = [NSAppleEventManager sharedAppleEventManager] SEL sel_ sharedAppleEventManager = sel_registerName("sharedAppleEventManager"); id mgr = objc_msgSend (objc_getClass("NSAppleEventManager"), sharedAppleEventManager); // and the rest SEL sel_setEventHandler = sel_registerName("setEventHandler:andSelector:forEventClass:andEventID:"); SEL sel_handleAppleEvent = sel_registerName("handleAppleEvent:withReplyEvent:"); objc_msgSend (mgr, sel_setEventHandler, targetObject, sel_handleAppleEvent, kInternetEventClass, kAEGetURL);
如您所见,我们在此处有两个子例程调用:第一个调用NSAppleEventManager
类的sharedAppleEventManager
消息,从该类中检索单个对象。 第二个调用是将setEventHandler …消息发送到该对象,传递4个参数(目标对象,目标消息和两个事件说明符)。
回调函数的声明,原来是:
- (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
在普通C中看起来像这样:
void handleAppleEvent (id self, SEL selector, NSAppleEventDescriptor* event, NSAppleEventDescriptor* replyEvent)
这意味着当调用函数时,它不仅会发送其对象引用(id),还会发送其方法占用(选择器)。
ObjC中的回调代码如下所示,以获取URL:
NSString url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
而在平原C:
id desc_id = objc_msgSend (event_id, sel_registerName("paramDescriptorForKeyword:"), '----'); id url_id = objc_msgSend (desc_id, desc_id, sel_registerName("stringValue"));
其中一部分仍然缺失:
targetObject
需要在调用上面的代码之前进行初始化,并且需要在该目标对象中创建与handleAppleEvent:withReplyEvent:
footprint匹配的方法,然后链接到我们的普通C事件处理程序( handleAppleEvent()
)。
这意味着我们必须创建一个Objective C类,向其中添加一个方法,然后创建一个它的对象实例:
// create an NSObject subclass for our target object char objcClassName[] = "ObjCAppleEventHandler"; id objcClass = objc_allocateClassPair (objc_getClass("NSObject"), objcClassName); // add the callback method to the class SEL sel_handleAppleEvent = sel_registerName("handleAppleEvent:withReplyEvent:"); class_addMethod (objcClass, sel_handleAppleEvent, handleAppleEvent, "i@:@@"); // register the class objc_registerClassPair (objcClass) // create an object instance id targetObject = class_createInstance (objcClass, 0); // ... here follows the above code with the setEventHandler invocation // (note: `SEL sel_handleAppleEvent` appears twice - the 2nd one can be removed)
这是普通的C版本。
(注意:上面的代码是在没有测试的情况下编写的,因此它可能包含错误。但是,下面的Java代码已经过测试。)
Java版本
从Plain C到Java的翻译现在相当简单。
上述ObjC Runtime函数都可以从org.eclipse.swt.internal.cocoa.OS获得。
首先,一些预设:
static final long class_NSAppleEventManager = OS.objc_getClass("NSAppleEventManager"); static final long sel_sharedAppleEventManager = OS.sel_registerName("sharedAppleEventManager"); static final long sel_setEventHandler = OS.sel_registerName("setEventHandler:andSelector:forEventClass:andEventID:"); static final long sel_handleAppleEvent = OS.sel_registerName("handleAppleEvent:withReplyEvent:"); static final long sel_paramDescriptorForKeyword = OS.sel_registerName("paramDescriptorForKeyword:"); static final long sel_stringValue = OS.sel_registerName("stringValue"); static final long kInternetEventClass = 0x4755524C; // 'GURL' static final long kAEGetURL = 0x4755524C; // 'GURL' static final long kCoreEventClass = 0x61657674; // 'aevt' static final long kAEOpenApplication = 0x6F617070; // 'oapp' static final long kAEReopenApplication = 0x72617070; // 'rapp' static final long keyDirectObject = 0x2d2d2d2d; // '----'
回调函数:
static long handleAppleEvent (long id, long sel, long event_id, long reply_id) { // This is a handler for AppleEvents that are registered with [NSAppleEventManager setEventHandler:...] // It matches this selector (footprint): // - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)reply // Invoke [[event paramDescriptorForKeyword:keyDirectObject] stringValue] to get the direct object containing the URL long direct_desc_id = OS.objc_msgSend (event_id, sel_paramDescriptorForKeyword, keyDirectObject); long direct_str_id = OS.objc_msgSend (direct_desc_id, sel_stringValue); NSString nsStr = new NSString (direct_str_id); String str = nsStr.getString(); // now 'str' contains the URL System.out.println ("handleAppleEvent invoked -- argument: "+url); return 0; }
以及注册回调函数的代码:
// Get access to a callback function for receiving the sel_handleAppleEvent message aeCallback = new Callback(Main.class, "handleAppleEvent", 4); long aeProc = aeCallback.getAddress(); // Create a ObjC class that provides a method with the sel_handleAppleEvent footprint String objcClassName = "ObjCAppleEventHandler"; long objcClass = OS.objc_allocateClassPair(OS.class_NSObject, objcClassName, 0); OS.class_addMethod(objcClass, sel_handleAppleEvent, aeProc, "i@:@@"); OS.objc_registerClassPair(objcClass); long objcHandlerInstance = OS.class_createInstance (objcClass, 0); // Invoke [[NSAppleEventManager sharedAppleEventManager] setEventHandler:objcHandlerInstance andSelector:sel_handleAppleEvent forEventClass:kInternetEventClass andEventID:kAEGetURL] long sharedAppleEventMgr = OS.objc_msgSend (class_NSAppleEventManager, sel_sharedAppleEventManager); OS.objc_msgSend (sharedAppleEventMgr, sel_setEventHandler, objcHandlerInstance, sel_handleAppleEvent, kInternetEventClass, kAEGetURL);
剩下要做的是从此代码构建应用程序包,然后将CFBundleURLTypes条目添加到其Info.plist中。
完整的示例源文件可以在这里下载: http : //files.tempel.org/Various/ObjectiveC-bridging.java.zip
如果有人想要使用com.apple.eawt的版本。*这也使用reflection,所以它将在任何平台(Windows等)上编译。 确保不要在任何非Apple系统上调用注册事件处理程序的方法;)
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; interface OpenUriAppleEventHandler { public void handleURI(URI uri); } class OpenURIEventInvocationHandler implements InvocationHandler { private OpenUriAppleEventHandler urlHandler; public OpenURIEventInvocationHandler(OpenUriAppleEventHandler urlHandler) { this.urlHandler = urlHandler; } @SuppressWarnings({ "rawtypes", "unchecked"}) public Object invoke(Object proxy, Method method, Object[] args) { if (method.getName().equals("openURI")) { try { Class openURIEventClass = Class.forName("com.apple.eawt.AppEvent$OpenURIEvent"); Method getURLMethod = openURIEventClass.getMethod("getURI"); //arg[0] should be an instance of OpenURIEvent URI uri = (URI)getURLMethod.invoke(args[0]); urlHandler.handleURI(uri); } catch (Exception ex) { ex.printStackTrace(); } } return null; } } public class OSXAppleEventHelper { /** * Call only on OS X */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void setOpenURIAppleEventHandler(OpenUriAppleEventHandler urlHandler) { try { Class applicationClass = Class.forName("com.apple.eawt.Application"); Method getApplicationMethod = applicationClass.getDeclaredMethod("getApplication", (Class[])null); Object application = getApplicationMethod.invoke(null, (Object[])null); Class openURIHandlerClass = Class.forName("com.apple.eawt.OpenURIHandler", false, applicationClass.getClassLoader()); Method setOpenURIHandlerMethod = applicationClass.getMethod("setOpenURIHandler", openURIHandlerClass); OpenURIEventInvocationHandler handler = new OpenURIEventInvocationHandler(urlHandler); Object openURIEvent = Proxy.newProxyInstance(openURIHandlerClass.getClassLoader(), new Class[] { openURIHandlerClass }, handler); setOpenURIHandlerMethod.invoke(application, openURIEvent); } catch (Exception ex) { ex.printStackTrace(); } } }
像这样用它:
//if(isOSX){ OSXAppleEventHelper.setOpenURIAppleEventHandler(new OpenUriAppleEventHandler() { @Override public void handleURI(URI url) { /* do something with the url */ } });
使用Java 9,这很容易,不再需要Apple的EAWT类或任何ObjC hackery。
Desktop.getDesktop().setOpenURIHandler((event) -> { System.out.println("Open URI: " + event.getURI()); // do something with the URI });
应用程序需要捆绑,并且必须设置CFBundleURLTypes键。
CFBundleURLTypes CFBundleURLSchemes example CFBundleURLName
不幸的是,只有在应用程序已经运行时才会捕获URI。 如果通过打开URI启动应用程序,则不会传递该事件(请参阅ed22的答案评论)。
- Gradle:如何使用并排项目配置多项目设置
- 如何禁用java.awt.Graphics.fillRect(int x,int y,int width,int height)的效果?
- 如何在netbeans中将jcombobox添加到jtable列
- 语法错误,插入“… VariableDeclaratorId”以完成FormalParameterList
- JPA。 JoinTable和两个JoinColumns
- 如何将Yeoman scaffolding与现有的Java目录结构相结合
- 自动部署到sonatype的oss maven存储库
- 同步跨线程共享但不同时访问的对象
- 如何使用Powermock模拟void静态方法抛出exception?