BlackBerry - background application to listen starts and foreground app

女生的网名这么多〃 提交于 2019-11-29 02:26:28

This is what you can do:

  • use ApplicationManager.getForegroundProcessId()
  • use ApplicationManager.getVisibleApplications() to get all running apps
  • use ApplicationManager.getProcessId() to search for app by process id
  • do this in TimerTask with defined period

    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);
        }
    }
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!