BlackBerry支持给它自带的一些应用程序添加自定义的菜单,并通过激活这些菜单来完成开发者自定义的事件,从而有效的扩展这些应用程序的功能。例如,在打开浏览收到短信息(SMS)的时候,在菜单中增加一项“Open with MyApp”的菜单项,点击该菜单项后会用自己的程序去处理短信息中包含的内容。
要实现这种功能需要用到应用程序菜单项API,该API在net.rim.blackberry.api.menuitem包中。ApplicationMenuItemRepository类让开发者可以加入或删除应用程序菜单项。它提供一些常量来定义一个菜单项显示的应用程序上下文.例如, 当浏览短信息的时候可以使用ApplicationMenuItemRepository.MENUITEM_SM_VIEW常量。ApplicationMenuItem抽象类定义了一个在应用程序菜单里显示的菜单项。下面将以具体的代码来解释整个步骤。
(1)创建菜单项:
class MyMenuItem extends ApplicationMenuItem{
}
该菜单项必须继承自ApplicationMebuItem。
(2)指定菜单项的位置:
开发者可以选择性的覆盖构造函数。在下面的代码实例中,构造子函数调用了ApplicationMenuItem(),它带有一个菜单项在菜单里的相对位置.(一个较大的数字意味着菜单项在菜单的较低位置)。
public MyMenuItem(){
Super(20);
}
(3)指定菜单项的文本:
toString()的实现指定了菜单项在菜单中显示的文本。
public String toString() {
return "Open with MyApp";
}
(4)指定菜单项的激活事件:
public Object run(Object context) {
MultipartMessage sMessage = (MultiPartMessage) context;
if ( sMessage ! null ) {
//open with My app
}
else
{
throw new IllegalStateException( "Context is null, expected a Contact instance");
}
Dialog.alert("Viewing a message in the messaging view");
return null;
}
这里因为要把菜单项加到短信息浏览上,根据API传入的参数类型必须是MultipartMessage。
(5)注册菜单项:
首先要获取应用程序菜单项库:
ApplicationMenuItemRepository repository =
ApplicationMenuItemRepository.getInstance();
接着定义一个静态唯一值:
long ID = 0×7cab1e23b72a0033L;
最后就将菜单项将入到菜单库:
repository.addMenuItem(ApplicationMenuItemRepository.MENUITEM_SMS_VIEW, new MyMenuItem);
这样就完成了菜单注入的开发。
详细代码如下:
package com.rim.samples.docs.menuitem;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.component.Dialog.*;
import net.rim.blackberry.api.menuitem.*;
import javax.microedition.pim.*;
import net.rim.device.api.pdap.*;
public final class DemoMenuItem extends Application {
private static long ID = 0×7cab1e23b72a0033L;
//com.rim.samples.docs.menuitem
public static void main(String[] args) {
DemoMenuItem app = new DemoMenuItem();
app.enterEventDispatcher();
}
DemoMenuItem() {
ApplicationMenuItemRepository amir =
ApplicationMenuItemRepository.getInstance();
amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_SMS_VIEW,
new MyMenuItem());
}
private static class MyMenuItem extends ApplicationMenuItem {
MyMenuItem() {
super(20);
}
public String toString() {
return "Open with MyApp";
}
public Object run(Object context) {
MultipartMessage sMessage = (MultiPartMessage) context;
if ( c ! null ) {
Dialog.alert("Open with MyApp at :" + sMessage.getUrl());
}
else {
throw new IllegalStateException( "Context is null, expected a Contact instance");
}
return null;
}
}
}