2009-12-28 152 views

回答

7

這是你可以做什麼:

  • 使用ApplicationManager.getForegroundProcessId()
  • 使用ApplicationManager.getVisibleApplications()來獲取所有正在運行的應用
  • 使用ApplicationManager.getProcessId()搜索應用程序進程的ID
  • TimerTask中定義期限

    public class AppListenerApp extends Application { 
    int mForegroundProcessId = -1; 
    
    public AppListenerApp() { 
        Timer timer = new Timer(); 
        timer.schedule(mCheckForeground, 2000, 2000);      
    } 
    
    public static void main(String[] args) { 
        AppListenerApp app = new AppListenerApp(); 
        app.enterEventDispatcher(); 
    } 
    
    TimerTask mCheckForeground = new TimerTask() { 
        public void run() { 
         int id = getForegroungProcessID(); 
         if(id != mForegroundProcessId) 
         { 
          mForegroundProcessId = id; 
          String name = 
           getAppNameByProcessId(mForegroundProcessId); 
          showMessage(name); 
         } 
        }; 
    }; 
    
    private int getForegroungProcessID() { 
        return ApplicationManager.getApplicationManager() 
          .getForegroundProcessId(); 
    } 
    
    private String getAppNameByProcessId(int id) { 
        String result = null; 
        ApplicationManager appMan = 
           ApplicationManager.getApplicationManager(); 
        ApplicationDescriptor appDes[] = 
           appMan.getVisibleApplications(); 
        for (int i = 0; i < appDes.length; i++) { 
         if (appMan.getProcessId(appDes[i]) == id) { 
          result = appDes[i].getName(); 
          break; 
         } 
        } 
        return result; 
    } 
    
    private void showMessage(String message) { 
        synchronized (Application.getEventLock()) { 
         Dialog dlg = new Dialog(Dialog.D_OK, message, 
             Dialog.OK, null, Manager.FIELD_HCENTER); 
         Ui.getUiEngine() 
             .pushGlobalScreen(dlg, 1, UiEngine.GLOBAL_QUEUE); 
        } 
    } 
    } 
    
+0

感謝您的答覆... 相反,那麼這是沒有任何監聽器API或任何類型的事件 ,通過它,我們將獲得當前調用的前臺應用程序。 – 2009-12-28 12:35:01

+0

如果您的應用程序,您可以隨時使用http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/system/Application.html#activate%28%29事件..但在其他情況下,我看不到任何選擇。 – 2009-12-28 15:15:32

+0

好的,謝謝你的回覆 – 2009-12-29 07:15:00