views:

597

answers:

1

Hi everyone! I would like to create background application which will listen to what applications are started and what are moved to foreground.

Please reply If question is not clear will explain again.

Thanks

+4  A: 

Hi! 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);
        }
    }
    }
    
Max Gontar
Thanks for the reply...Rather then this is there any Listener API or any kind of Event through which we will get the current invoked Foreground Application.
RockOn
If its your application, you can always use http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/system/Application.html#activate%28%29 event... but in other cases I see no option.
Max Gontar
Ok thanks for ur reply
RockOn
You're welcome!
Max Gontar