Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
rajani_dhawan
Posts: 55
Registered: ‎05-30-2011
My Carrier: Airtel
Accepted Solution

global event listener is not called instantly and properly on device.

[ Edited ]

hi friends,

 

I am trying to develop an application, from which i can select  any native, inbuld application of  BB device to block.

So when ever any app comes to foreground,  I have to check whether this application belongs to "block application list or not".   I implement "GlobalEventLlistener" to  handle this task.  I use BB jre 4.7 ,  It is work properly on simulator but not on the device. 

 

here is the main uiapplication code...where i implement GlobalEventListener.

For storing the block application names, i use Local Storage.

 

 


package mypackage;


import java.util.Vector;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.system.EventInjector;
import net.rim.device.api.system.GlobalEventListener;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.system.EventInjector.KeyCodeEvent;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.DialogFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;

/**
 * This class extends the UiApplication class, providing a
 * graphical user interface.
 */
public class MyApp extends UiApplication implements GlobalEventListener
{
	private Screen popup = null;
	private Screen popupErr = null;
	private static int processID = -1;
	
    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */ 
    public static void main(String[] args)
    {
        // Create a new instance of the application and make the currently
        // running thread the application's event dispatch thread.
    	
		MyApp theApp = new MyApp();       
        theApp.enterEventDispatcher();      
        
    }
    
    
    /**
     * Creates a new MyApp object
     * @param appNames 
     */
    public MyApp()
    {        
        
    	try {
			Thread _thread = new Thread(new CheckRequest());
			_thread.start();
		} catch (Exception e) {
			System.out.println("\n\n**** Excep in MyApp 1 : " + e.toString() + "\n");
		}
    }   
    
    class CheckRequest extends Thread {
		public void run() {
			// Creates an instance of the system’s application manager.
			ApplicationManager myApp = ApplicationManager
					.getApplicationManager();
			while (myApp.inStartup()) {
				try {
					Thread.sleep(20000);
				} catch (Exception e) {
					System.out.println("\n\n**** Excep in MyApp 2 : " + e.toString() + "\n");
				}
			}
			
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
										
					startUp();
				}
			});
		}
	}

    void startUp() {
    	try {
    		
    		GlobalVars.app = this;
    		String arr [] = null;
    		try {
    			arr = GetAllAppNames.getNames();				
			} catch (Exception e) {
				GlobalVars.DB_INITIALIZED = false;
				System.out.println("\n\n**** Excep in MyApp 4 : " + e.toString() + "\n");
			}
			
    		//LocalStorage.deleteAllAppRecord();
    		net.rim.device.api.ui.container.MainScreen thisScreen = new AppDemoScreen(arr);
        	
        	
        	GlobalSingleton obj = null;
        	obj = GlobalSingleton.getInstance();
        	obj.setAcceptsForeground(true);
        	obj.setApp(GlobalVars.app);
        	obj.setShowDialog(false);
        	
        	pushScreen(thisScreen);
        	requestForeground();
        	
        	obj.setCpScreen(thisScreen);
        	
        	
        	this.addGlobalEventListener(this);
    		
    	} catch (Exception e) {
    		System.out.println("\n\n**** Excep in MyApp 3 : " + e.toString() + "\n");
		}
    }


	public void eventOccurred(long guid, int data0, int data1, Object object0,
			Object object1) {
		
		processID = ApplicationManager.getApplicationManager().getForegroundProcessId();

		GlobalSingleton obj = null;
    	obj = GlobalSingleton.getInstance();
    	
    	if( processID == -1 ) {
    		obj.setShowDialog(false);
			obj.setUnlockStatus(false);
			obj.setUnBlockApp(false);
			obj.setPrePID(-1);
			
			return;
    	} else if(
    			( obj.getHomeScreenPID() == processID )|| 
    			( obj.getShowDialog() ) || 
    			( obj.getPrePID() == processID ) ) // && obj.getUnBlockApp() ||
    			// ( obj.getPrePID() == processID ) && obj.getUnlockStatus())
    		return; 
    	
		/* 
		 * find module name and localized name into LocalStorage and if found
		 * then send current foreground application into background. 
		 */
		if(comparePID()) {
			// show popup screen
			synchronized(Application.getEventLock()) {
				unlockField();					
			}
		}
    	 	
	}
    
	/*
	 * get all system application - descriptor names ; 
	 * get process ID from AppManager for AppDes and and compare with current process id. 
	 * 
	 */
	private boolean comparePID() {
		boolean _runLoop = true;
		boolean _return = false;
		//String appName = "";
		
		GlobalSingleton obj = null;
    	obj = GlobalSingleton.getInstance();
    	
		try {
			ApplicationManager appMan = 
            	ApplicationManager.getApplicationManager();
			
			Vector _vTemp = LocalStorage.getAppRecords();
			String _modules[][] = new String [_vTemp.size()][2];
			
			for (int i = 0 ; i < _vTemp.size() && _runLoop ; i++) {
				_modules[i] = Util.split(_vTemp.elementAt(i).toString(), "$");
				
				int modHandle = CodeModuleManager.getModuleHandle(_modules[i][0]);
				
				ApplicationDescriptor descriptors[] = 
					CodeModuleManager.getApplicationDescriptors(modHandle);
				
				for (int j=0 ; j < descriptors.length && _runLoop ; j++) {
					int pid = appMan.getProcessId(descriptors[j]);
					String localName = descriptors[j].getLocalizedName();
					System.out.println("\n\n**** MyEventListener : Local Name : " + localName + "\n");
					
					if ( (pid==processID) && (CommonAppNames._isNotAppName(localName)) ) {
						_runLoop = false;
						obj.setPrePID(processID);
						obj.setUnBlockApp(true);
					}	
					else if( (pid==processID) && !CommonAppNames._isNotAppName(localName)) {
						 
						 _return = true;
						 _runLoop = false;
						 obj.setPrePID(processID);
						 obj.setUnBlockApp(false);
					}
				}				
			}		
						
		} catch (Exception e) {
			_return = false;
			System.out.println("\n\n**** Excep in : MyEventListener 2 : " + e.toString() + "\n");
		}
		return _return;
	}
	
	/*
	 * push global Dialog box...
	 */
	private void unlockField() {
		try {
			GlobalSingleton obj = null;
        	obj = GlobalSingleton.getInstance();
        	obj.setShowDialog(true);
        	
			DialogFieldManager manager = new DialogFieldManager();
			final EditField ef = new EditField();
			
			ButtonField unlock = new ButtonField("Unlock");		
			FieldChangeListener FCLCheckPin = new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					String pin = ef.getText();

					if (pin.equals("1111")) {
						try {
							GlobalSingleton obj = null;
				        	obj = GlobalSingleton.getInstance();
				        	Screen _popup = obj.getPopupScreen();
				        	obj.setShowDialog(false);
							obj.setUnlockStatus(true);
							obj.setPrePID(processID);
							
//							Ui.getUiEngine().popScreen(_popup);
							UiApplication.getUiApplication().popScreen(_popup);
							
						} catch (Exception e) {
							System.out.println("\n\n**** Excep in : MyEventListener 3 : " + e.toString() + "\n");
						}
					} else {
						try {
							
							showPopupErr();
							
						} catch (Exception e) {
							System.out.println("\n\n**** Excep in : MyEventListener 3_1  : " + e.toString() + "\n");
						}
					}
				}
			};		
			unlock.setChangeListener(FCLCheckPin);
			
			ButtonField cancel = new ButtonField("Cancel");
			FieldChangeListener FCLCancel = new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						
					}
					GlobalSingleton obj = null;
		        	obj = GlobalSingleton.getInstance();
		        	Screen _popup = obj.getPopupScreen();
		        	obj.setShowDialog(false);
					obj.setUnlockStatus(false);
					
					obj.setPrePID(-1);
					
//					Ui.getUiEngine().popScreen(_popup);
					UiApplication.getUiApplication().popScreen(_popup);
					
					// close or exit the current foreground application.
					exitCurrentFGApp();
				}
			};		
			cancel.setChangeListener(FCLCancel);
			
			HorizontalFieldManager hfm = new HorizontalFieldManager(
					Field.FIELD_HCENTER);
			hfm.add(unlock);
			hfm.add(cancel);
			
			manager.addCustomField(ef);
			manager.addCustomField(hfm);
			
			popup = new PopupScreen(manager);
			obj.setPopupScreen(popup);
			
//			Ui.getUiEngine().pushGlobalScreen(popup, 1,
//					UiEngine.GLOBAL_MODAL);
			UiApplication.getUiApplication().pushGlobalScreen(popup, 1,
					UiEngine.GLOBAL_MODAL);
			
		} catch (Exception e) {
			System.out.println("\n\n**** Excep in : MyEventListener 4 : " + e.toString() + "\n");
		}				
	}
	
	private void showPopupErr() {
		try {
			GlobalSingleton obj = null;
        	obj = GlobalSingleton.getInstance();
        	obj.setShowDialog(true);
        	
			DialogFieldManager manager = new DialogFieldManager();
			
			LabelField lbl = new LabelField("Wrong PIN number.", LabelField.FIELD_HCENTER | 
					LabelField.FIELD_VCENTER | LabelField.HCENTER | LabelField.VCENTER);
			
			ButtonField okBtn = new ButtonField("OK");		
			FieldChangeListener okHandle = new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					GlobalSingleton obj = null;
		        	obj = GlobalSingleton.getInstance();
		        	Screen _popup1 = obj.getPopupErrScreen();
		        	
					UiApplication.getUiApplication().popScreen(_popup1);
				}
			};		
			okBtn.setChangeListener(okHandle);
			
			HorizontalFieldManager hfm = new HorizontalFieldManager(Field.FIELD_HCENTER);
			hfm.add(okBtn);
			
			manager.addCustomField(lbl);
			manager.addCustomField(hfm);
			
			popupErr = new PopupScreen(manager);
			obj.setPopupErrScreen(popupErr);
			
//			Ui.getUiEngine().pushGlobalScreen(popup, 1,
//					UiEngine.GLOBAL_MODAL);
			UiApplication.getUiApplication().pushGlobalScreen(popupErr, 1,
					UiEngine.GLOBAL_MODAL);
			
		} catch (Exception e) {
			System.out.println("\n\n**** Excep in : MyEventListener 4 : " + e.toString() + "\n");
		}				
	}
	
	/*
	 * exit current opened foreground application
	 */
	private void exitCurrentFGApp() {
		try {
		
		EventInjector.KeyCodeEvent pressKey=new EventInjector.KeyCodeEvent(
				KeyCodeEvent.KEY_DOWN, (char) Keypad.KEY_ESCAPE,
				KeypadListener.STATUS_ALT); 
		
		EventInjector.KeyCodeEvent releaseKey=new EventInjector.KeyCodeEvent(
				KeyCodeEvent.KEY_UP, (char) Keypad.KEY_ESCAPE,
				KeypadListener.STATUS_ALT);
		
		EventInjector.invokeEvent(pressKey);
		EventInjector.invokeEvent(releaseKey);
        Thread.sleep(500);
//        EventInjector.invokeEvent(pressKey);
//        EventInjector.invokeEvent(releaseKey);
        
		} catch (InterruptedException e) {
			System.out.println("\n\n**** Excep in : MyEventListener 5 : " + e.toString() + "\n");
		}		
	}	
    
}

 

Function comparePID()  will compare current Foreground application's process id only with those application's which module names are stored in Local storage. If founds then  return true else return  false.

 

 

Code is working  on simulator properly  but  when i test it on  the device... Listener is not called properly.

 

I have test this on BB storm 9500, and BB Flip - 8220. When i load the app ondevice,  some time GlobalEventListener called  but  some time not..

 

How this can be done??  Please give some suggestion. 

 

thnaks in  advance.

Please use plain text.
Developer
peter_strange
Posts: 19,521
Registered: ‎07-14-2008

Re: global event listener is not called instantly and properly on device.

[ Edited ]

Am I right in saying that your code depends on there being a GlobalEvent initiated when an app is bought to the foreground?  It doesn't matter what the event is?

 

So your problem is that in some OS's there is no Global Event when the app is bought to the foreground. You will pick up that the app shouldn't be there the next time a globalEvent is initiated, but that could be done time after it comes to the foreground.

 

If this is not your problem, please can you explain again?

 

BTW:  I am not aware that RIM documented that a Global Event would be triggered when an app is bought to the foreground.

Please use plain text.
Developer
rajani_dhawan
Posts: 55
Registered: ‎05-30-2011
My Carrier: Airtel

Re: global event listener is not called instantly and properly on device.

Thanks for ur attention Peter..

 

Basically I want to develop an app which can “restrict the invocation of applications (built-in or third party) on BlackBerry device”, when we hand it over to another person for temporary use.

 

On startup my application gets stared and the show a screen with list of applications (installed on that BB device), list can be modified anytime.

 

 

 

 

Selected application list (module names) will be stored in Local Storage.

 

For example if  calendar, contact, browser, call log, media applications is stored in the  block list, then whenever user  open these apps, they will  block by a popup screen, user hv to enter right  PIN number,  and only then can unblock that application.

 

 

 

When ever I tried to search that how the blocking of applications is possible when they comes to the foreground, I always find the links containing GlobalEventListener.

 

So that’s why  I  used that. My demo application is running on simulator properly when I tried to test it on the device…GlobalEventListener not called properly. Some time it is called and some time not.

 

I cant undderstand what’s wrong here.

Please tell me where I am wrong… Is there some other mechanism(event type or listener), used for the blocking of invocations of the applications…..????

 

I have tried free version of Mr. Safe Application, from the blackberry application world. It blocks selected  applications successfully. You can see it on the following link : “Mr. Safe".

Mr.Safe

 

 

Yes! My basic requirement is to catch that particular global-event initiated when an app is bought to the foreground... so that i can block that application. Would u tell me whst kind of global event triggered when an application comes to the foreground..

 

thaks for ur response..

 

 

 

Please use plain text.
Developer
peter_strange
Posts: 19,521
Registered: ‎07-14-2008

Re: global event listener is not called instantly and properly on device.

I have not seen Threads can match this description:

 

"When ever I tried to search that how the blocking of applications is possible when they comes to the foreground, I always find the links containing GlobalEventListener."

 

Can you please point me at any that say this.  I would like to review them, as I suspect they are either incorrect or you have not interpreted them correctly.

 

"My basic requirement is to catch that particular global-event initiated when an app is bought to the foreground"

 

Sorry, as I noted previously, I am not aware of a GlobalEvent that RIM says will happen when an application is bought to the foreground.  So as far as i am concerned, listening for a Global Event is not an appropriate way to detect this switch because

a) It does not get called, and

b) You will checking loads of Global Events that are not in fact related to your apps processing.

 

As far as I am aware, most apps that 'block' do so by having a background Thread than frequently checks what app is running in the foreground.  This is done on a Timer not a Global Event. 

 

But happy to be proved wrong.

Please use plain text.
Developer
rajani_dhawan
Posts: 55
Registered: ‎05-30-2011
My Carrier: Airtel

Re: global event listener is not called instantly and properly on device.

Hi Peter, thanks for ur support.

 

according to ur suggestion i hv replaced my code with a Timer Thread and schdule that timer for a 1 sec interval.

 

Now this timer successfully compares the "native app" for e.g. calendar with the block app list, and if matches then open a popup screen having:

textfield (for pin number), unlock and cancel button as above I show above.

 

But now I m facing a new problem:

On the invocation of any block application, my app’s background thread opens popup-screen as show above. 1.) If user enter correct pin number then popup-screen will be closed using "UiApplication.getUiApplication().popScreen(popupScreenObj).... and after then native app will have the focus.

 

2.) But in case user click on the cancel button, I have to close the native application also after the popup-screen.

 

But till yet I didn’t find any method for that, how
1.            We can pass “escape key” event to the native application (from the background thread of other application) OR
2.            We can get the menu of the native application (from the background thread of other application) to execute the “close” command of that native application.

 

One more approach, I want to discuss, if we send the native block application to background, then is there any way to kill that background process further. So that when user clicks the cancel button we can kill that native application’s background process using its process id. But I don’t think this is the right approach, because there are some applications like browser, phone, home-screen, messages which always run in the background and we can’t kill them.

 

pls tell me, how can we close that native app, from my background app's thread. I want to do this task as early as possible, bt now i hv stuck here...

 

Let me one know one thing, did u tried the  trial version of  Mr. Safe application, i told earlier. It does this blocking task very smoothly. So it is sure that there must be a way to block / close any native application from some other background process in BB environment.

 

thanks.

 

Please use plain text.
Developer
simon_hain
Posts: 15,558
Registered: ‎07-29-2008
My Carrier: O2 Germany

Re: global event listener is not called instantly and properly on device.

you cannot kill the system application, but you can put another application to the foreground.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
rajani_dhawan
Posts: 55
Registered: ‎05-30-2011
My Carrier: Airtel

Re: global event listener is not called instantly and properly on device.

ok simon. bt how can we close any native application... from other third party app's thread.

 

i hope as u read that this is main task of my app.  :smileysad:

 

 

Please use plain text.
Developer
simon_hain
Posts: 15,558
Registered: ‎07-29-2008
My Carrier: O2 Germany

Re: global event listener is not called instantly and properly on device.

i just said that you cannot close another application.
these blocker apps just put something else in the foreground, this puts the native app in the background (sounds logical?).
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
peter_strange
Posts: 19,521
Registered: ‎07-14-2008

Re: global event listener is not called instantly and properly on device.

[ Edited ]

I believe you can, from another application, use Event Injection to simulate say the "ESC" button, or other keystrokes to close another Application that is running in the foreground.  That assumes you know exactly how to do this, and the user does not get in the way.

 

For me this is dubious option, I can see to many possibilities for this to go wrong. 

 

I know of no other way of doing anything like this sorry.

Please use plain text.
Developer
rajani_dhawan
Posts: 55
Registered: ‎05-30-2011
My Carrier: Airtel

Re: global event listener is not called instantly and properly on device.

thanks guys, for giving support.

 

i have already tried to close the app... through event injection.. but even after the function takes place...  native app doesn't close..

 

private void exitCurrentFGApp() {
        try {
        
        EventInjector.KeyCodeEvent pressKey=new EventInjector.KeyCodeEvent(
                EventInjector.KeyCodeEvent.KEY_DOWN, ((char) Keypad.KEY_ESCAPE),
                KeypadListener.STATUS_NOT_FROM_KEYPAD);
        
        EventInjector.KeyCodeEvent releaseKey=new EventInjector.KeyCodeEvent(
                EventInjector.KeyCodeEvent.KEY_UP, ((char) Keypad.KEY_ESCAPE),
                KeypadListener.STATUS_NOT_FROM_KEYPAD);
        
        EventInjector.invokeEvent(pressKey);
        EventInjector.invokeEvent(releaseKey);
        Thread.sleep(500);
        EventInjector.invokeEvent(pressKey);
        EventInjector.invokeEvent(releaseKey);
        
        } catch (Exception e) {
            System.out.println("\n\n**** Excep in : MyEventListener 5 : " + e.toString() + "\n");
        }        
    }       

 

and simon... would u pls discribe in detail....

"these blocker apps just put something else in the foreground, this puts the native app in the background (sounds logical?)."

 

bt i dont want  to send native apps into background.... because in that case they will be shown into Application Switcher.

 

and as i told earlier, i hv tried the Mr. Safe app's trial version.... on my BB device. it does this task very smoothly......block (close - not send to background) any native application of BB device.

 

 

Please use plain text.