2013-02-09 227 views
1

如何使用dbus导出java方法或对象?使用dbus调用java方法

我写这篇文章是因为官方文档非常差,花了我几个小时才弄清楚如何去做。

理想情况下的DBus接口应该在java包去

回答

2

DBus.java

import org.freedesktop.dbus.DBusInterface; 
import org.freedesktop.dbus.DBusInterfaceName;  

@DBusInterfaceName("org.printer") 
public interface DBus extends DBusInterface { 
    //Methods to export 
    public void Print(String message); 
} 

Main.java

import org.freedesktop.dbus.DBusConnection; 
import org.freedesktop.dbus.exceptions.DBusException; 

public class Main {  
    public static void main(String[] args) { 
     Printer p = new Printer(); 

     try { 
      DBusConnection conn = DBusConnection.getConnection(DBusConnection.SESSION); 
      //Creates a bus name, it must contain some dots. 
      conn.requestBusName("org.printer"); 
      //Exports the printer object 
      conn.exportObject("/org/printer/MessagePrinter", p); 
     } catch (DBusException DBe) { 
      DBe.printStackTrace(); 
      conn.disconnect(); 
      return; 
     } 
    } 
} 

//Printer object, implements the dbus interface and gets 
//called when the methods are invoked. 
class Printer implements DBus { 
    public boolean isRemote() { 
     return false; 
    } 

    public void Print(String message) { 
     System.out.println(message); 
    } 
} 

您可以用qdbus尝试了这一点外壳,运行:

qdbus org.printer /org/printer/MessagePrinter org.printer.Print test