How to create a simple service for your bundle?
Environment information:
OS: Fedora core 5
IDE: Eclipse 3.2.0
JRE:1.6.0 update 7
Knopflerfish: Release 2.0.0 (Knopflerfish OSGi Desktop Version 2.0.1)
1. Create a manifest.mf file
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: FirstService
Bundle-SymbolicName: FirstService
Bundle-Version: 1.0.0
Bundle-Activator: firstservice.Activator
Bundle-Localization: plugin
Import-Package: org.osgi.framework;version="1.3.0"
Export-Package: firstservice
Note:attention the"Export-Package" it's in your source code's destination.
2. create the service interface
package firstservice;
import java.util.Date;
public interface FirstService {
public String getFormatteDate(Date date);
}
3. create the service implementation
package firstservice;
import java.text.DateFormat;
import java.util.Date;
import firstservice.FirstService;
public class FirstServiceImpl implements FirstService {
public String getFormattedDate( Date date ){
return DateFormat.getDateInstance( DateFormat.SHORT ).format(date);
}
public String getFormatteDate(Date date) {
return null;
}
}
Note:In the KF documents the abstract is not exist, but in the java API, the DateFormat.getDateInstance() is need a abstract ,so I write two getFormatteDate() method, one for wok,another to return null.
4. create an Activator that Registers the Service
package firstservice;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import firstservice.FirstService;
public class Activator implements BundleActivator {
public static BundleContext bc = null;
public void start(BundleContext bc) throws Exception {
System.out.println( bc.getBundle().getHeaders().get( Constants.BUNDLE_NAME ) + " starting... " );
Activator.bc = bc;
FirstService service = new FirstServiceImpl();
final ServiceRegistration registration =
bc.registerService(FirstService.class.getName(), service, new Hashtable());
System.out.println("Service registered: FirstServuce");
}
public void stop(BundleContext context) throws Exception {
System.out.println(bc.getBundle().getHeaders().get( Constants.BUNDLE_NAME ) + " stopping... ");
Activator.bc = null;
}
}
Note:In the KF documents, the variable: registration doesn't declare for 'final',and went you compile the code, you will get a warnings because the registration is never read.
I'm not sure for this one. I will test it more and more.
5. Now, build it and run in KF Desktop.
Author: YuRu-Wei 2008/10/01 @ Shu-Te University CSIE Lab
- Oct 01 Wed 2008 23:22
[電腦]Creating a simple Service
close
全站熱搜
留言列表
禁止留言