增加黑莓程序自定義菜單項

 BlackBerry支持給它自帶的一些應用程序添加自定義的菜單,並通過激活這些菜單來完成開發者自定義的事件,從而有效的擴展這些應用程序的功能。例如,在打開瀏覽收到短信息(SMS)的時候,在菜單中增加一項“Open with MyApp”的菜單項,點擊該菜單項後會用自己的程序去處理短信息中包含的內容


要實現這種功能需要用到應用程序菜單項API,該APInet.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;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章