Create an application which will lock another application event - blackberry

Actually I want to make an application which will getGlobalEvent and control that event through another custom application. Is there any way to do so. Can i get global event from a particular application? Its like an application which will lock custom application in your blackberry, if you add following application in that locking app list and put password to access then when u try to open that application, it will ask for a password which u set in the locking app.

Common advices
this should be background application
in timer thread check current foreground application
use custom global modal dialog to request password
if password was wrong close app by simulating back key press or move app to background
Checking Application
Have to say, there can be several processes within one application so we will perform check based on module name:
private String getModuleNameByProcessId(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].getModuleName();
break;
}
}
return result;
}
Move application to Background?
Yep, there's no requestBackground() in ApplicationManager... so what you can do is requestForeground() on the next best app which is not on foreground, and this will move active app to background! You can even bring up Home Screen with requestForegroundForConsole():
protected int switchForegroundModule() {
int id = -1;
ApplicationManager appMan = ApplicationManager.getApplicationManager();
ApplicationDescriptor appDes[] = appMan.getVisibleApplications();
for (int i = 0; i < appDes.length; i++) {
if (!appDes[i].getModuleName().equalsIgnoreCase(STR_MODULE_NAME)) {
id = appMan.getProcessId(appDes[i]);
appMan.requestForeground(id);
// give a time to foreground application
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
}
return id;
}
Global Dialog
Just to input password you can extend Dialog, it will be easier to consume result:
class PaswordDialog extends Dialog {
private BasicEditField mPwdField = new BasicEditField();
public PaswordDialog() {
super(Dialog.D_OK_CANCEL, "Enter password", Dialog.CANCEL, null,
Dialog.FIELD_HCENTER);
add(mPwdField);
}
public String getPassword() {
return mPwdField.getText();
}
}
And password check will look like:
private boolean checkPassword() {
boolean result = false;
final PaswordDialog pwdDlg = new PaswordDialog();
invokeAndWait(new Runnable() {
public void run() {
Ui.getUiEngine().pushGlobalScreen(pwdDlg, 0,
UiEngine.GLOBAL_MODAL);
}
});
result = ((Dialog.OK == pwdDlg.getSelectedValue()) && pwdDlg
.getPassword().equalsIgnoreCase(STR_PASSWORD));
return result;
}
Put this all together
Sample to block Adress Book App:
public class LockMainApp extends Application {
private static final String STR_MODULE_NAME = "net_rim_bb_addressbook_app";
private static final String STR_PASSWORD = "12345";
int mFGProcessId = -1;
public LockMainApp() {
Timer timer = new Timer();
timer.schedule(mCheckForeground, 1000, 1000);
}
public static void main(String[] args) {
LockMainApp app = new LockMainApp();
app.enterEventDispatcher();
}
TimerTask mCheckForeground = new TimerTask() {
public void run() {
int id = ApplicationManager
.getApplicationManager().getForegroundProcessId();
if (id != mFGProcessId) {
mFGProcessId= id;
String moduleName = getModuleNameByProcessId(mFGProcessId);
if (moduleName.equalsIgnoreCase(STR_MODULE_NAME)) {
if (!checkPassword())
mFGProcessId = switchForegroundModule();
}
}
};
};
}

Related

Blackberry - Clickable BitmapField With Different ID's

i'm creating one application in which i get gift images with id's from web server through JSON. When i click on any gift image, it goes on next page where it shows all information of that image (get image information with its id from web server through JSON).
Problem is: When i click on any gift image on page to see its relevant information, it gets the last gift image id every time, i want when i click on any image, it gets the specific image id which i click. How it is possible??
Screenshot of the page is : http://ugo.offroadstudios.com/gifts.png
Here is sample code:
public class Gifts extends MainScreen {
String giftsid;
BitmapField giftimg;
public Gifts(){
setTitle("Gift Store");
creategifts();
}
public void creategifts()
{
//Link URL
String strURL = "http://ugo.offroadstudios.com/api/frndgift/?loginusername=adil;deviceside=true";
webConnection wb = new webConnection();
String res = wb.getJson(strURL);
try {
JSONObject object = new JSONObject(res);
if(object.getString("status") == "error")
{
Dialog.alert("Invalid "+object.getString("status"));
}
else
{
int totalgifts;
totalgifts = object.getInt("totalgifts");
Bitmap listThumb;
JSONArray imagearr;
JSONArray giftsidarr;
String imgname;
Bitmap bmpResized;
for(int i=0; i < totalgifts; i++){
imagearr = object.getJSONArray("gifts_image");
imgname = imagearr.getString(i);
giftsidarr = object.getJSONArray("gifts_id");
giftsid = giftsidarr.getString(i);
listThumb = getImage.getImageFromUrl("http://ugo.offroadstudios.com/wp-content/plugins/bp-gifts-rebirth/includes/images/"+imgname+";deviceside=true");
bmpResized = GPATools.ResizeTransparentBitmap(listThumb, 80, 80,
Bitmap.FILTER_LANCZOS, Bitmap.SCALE_TO_FIT);
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("giftsid "+giftsid);
UiApplication.getUiApplication().pushScreen(new SendGift(giftsid));
return true;
}
};
add(giftimg);
}
}
}
catch (JSONException e) {
System.out.println("EX is "+e);
e.printStackTrace();
}
}
}
You are always getting the gift id of the last gift in the list because you have created your buttons with this code:
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("giftsid "+giftsid);
UiApplication.getUiApplication().pushScreen(new SendGift(giftsid));
return true;
}
};
Your navigationClick() method used the giftsid variable, which is a persistent member variable of your class. You assign this variable in your for loop, so the final value it keeps is the last value assigned in the loop (giftsidarr.getString(totalgifts)).
Although you declare the navigationClick() method in a loop where the giftsid is many different values, the navigationClick() method uses the value of giftsid when it is run. The last value.
There's many ways to fix it. You can use a separate constant value in your loop:
final String nextGiftsId = giftsid;
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("nextGiftsId= "+nextGiftsId);
UiApplication.getUiApplication().pushScreen(new SendGift(nextGiftsId));
return true;
}
};
Or, as Signare suggested, attach a cookie to each button that identifies its corresponding gift:
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
String giftId = (String)getCookie(); // read gift id from the cookie
Dialog.alert("giftId= "+giftId);
UiApplication.getUiApplication().pushScreen(new SendGift(giftId));
return true;
}
};
giftimg.setCookie(giftsid); // set the cookie after creating the field
Inside your for loop, add the following code -
giftimg[i].setChangeListener(this);
Then -
public void fieldChanged(Field field, int context) {
for(int i=0;i<totalgifts;i++) {
if(field == giftimg[i]) {
// you can trigger your event
}
}
EDIT :-
giftimg[i].setChangeListener(listener);
listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if ( field instanceof BitmapField ) {
for(int i=0;i<totalgifts;i++) {
if ( field == giftimg[i] ) {
// you can trigger your event
}
}
}
}
};

Launching the application from an url in the browser for BlackBerry?

I am developing one application where i will launch a url in the browser from which i will launch my application.
Suppose if i will click google.com, and press enter, it will launch my application. For that i tried with the HttpFilterRegistry API.
For reference i am using the HTTPFilterDemo application. But currently while launching the app, i am getting the NullPointerException.
I wrote the below code i the openFilter Method:
public Connection openFilter(String name, int mode, boolean timeouts) throws IOException {
Logger.out("Protocol", "it is inside the openFilter method");
_url = name.substring(2);
_requestHeaders = new HttpHeaders();
_responseHeaders = new HttpHeaders();
_responseHeaders.setProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, "text/html");
Logger.out("Protocol", "here it is come ::::44444444");
final int modHandle = CodeModuleManager.getModuleHandle("AppLaunchBrowser");
Logger.out("Protocol", "here is the module handle:::" + modHandle);
final ApplicationDescriptor[] apDes = CodeModuleManager.getApplicationDescriptors(modHandle);
final ApplicationDescriptor appDescriptor = new ApplicationDescriptor(apDes[0], new String[] {});
Logger.out("Protocol", "here is the app descriptor:::" + appDescriptor);
try {
final int appCode = ApplicationManager.getApplicationManager().runApplication(appDescriptor, true);
Logger.out("Protocol", "here is the app code:::" + appCode);
} catch (ApplicationManagerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return this;
}
And in the application class i am creating alternative entry point and using like below:
public class AppLaunch extends UiApplication{
public static void main(String args[])
{
Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
if((args != null) && (args.length > 0) && (args[0].equals("background")))
{
Logger.out("AppLaunch", "in the alternate entry point");
// Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
else
{
Logger.out("AppLaunch", "Inside the Applaunch");
AppLaunch theApp = new AppLaunch();
theApp.requestForeground();
Logger.out("AppLaunch", "created the app launch object");
theApp.enterEventDispatcher();
// Logger.out("AppLaunch", "in the alternate entry point");
// HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
}
public AppLaunch()
{
checkPermissions();
showTestScreen();
}
private void checkPermissions()
{
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if(original.getPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER) == ApplicationPermissions.VALUE_ALLOW)
{
// All of the necessary permissions are currently available
return;
}
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if(acceptance)
{
// User has accepted all of the permissions
return;
}
else
{
}
}
private void showTestScreen()
{
UiApplication.getUiApplication().pushScreen(new AppLaunchScreen());
}
}
Finally i was able to resolve this issue. Actually NPE is coming in some other callback methods because i was implementing the FilterBaseInterface.

Backup/Restore net.rim.device.api.util.Persitable object with DesktopManger

The task is to backup/restore Persistable object with BB Desktop Manager or in any other way. The main aim is to keep data between device firmware updates...
I have:
public final class UserList implements Persistable {
//The persistable objects.
private Hashtable fData;
//Initialize the class with empty values.
public UserList() {
fData = new Hashtable();
}
//Initialize the class with the specified values.
public UserList(Hashtable p) {
fData = p;
}
public Hashtable getData() {
return fData;
}}
I also have implemented SyncItem (as found in one of the examples)
public final class UserListSync extends SyncItem {
private static UserList fList;
private static final int FIELDTAG_NAME = 1;
private static final int FIELDTAG_AGE = 2;
private static PersistentObject store;
static {
store = PersistentStore.getPersistentObject(0x3167239af4aa40fL);
}
public UserListSync() {
}
public String getSyncName() {
return "Sync Item Sample";
}
public String getSyncName(Locale locale) {
return null;
}
public int getSyncVersion() {
return 1;
}
public boolean getSyncData(DataBuffer db, int version) {
boolean retVal = true;
synchronized (store) {
if (store.getContents() != null) {
fList = (UserList)store.getContents();
}
}
try {
Enumeration e = fList.getData().keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) fList.getData().get(key);
//Write the name.
db.writeShort(key.length() + 1);
db.writeByte(FIELDTAG_NAME);
db.write(key.getBytes());
db.writeByte(0);
//Write the age.
db.writeShort(value.length() + 1);
db.writeByte(FIELDTAG_AGE);
db.write(value.getBytes());
db.writeByte(0);
}
} catch (Exception e) {
retVal = false;
}
return retVal;
}
//Interprets and stores the data sent from the Desktop Manager.
public boolean setSyncData(DataBuffer db, int version) {
int length;
Hashtable table = new Hashtable();
Vector keys = new Vector();
Vector values = new Vector();
boolean retVal = true;
try {
//Read until the end of the Databuffer.
while (db.available() > 0) {
//Read the length of the data.
length = db.readShort();
//Set the byte array to the length of the data.
byte[] bytes = new byte[length];
//Determine the type of data to be read (name or age).
switch (db.readByte()) {
case FIELDTAG_NAME:
db.readFully(bytes);
keys.addElement(new String(bytes).trim());
break;
case FIELDTAG_AGE:
db.readFully(bytes);
values.addElement(new String(bytes).trim());
break;
}
}
} catch (Exception e) {
retVal = false;
}
for (int i = 0; i < keys.size(); i++) {
table.put(keys.elementAt(i), values.elementAt(i));
}
try {
//Store the new data in the persistent store object.
fList = new UserList(table);
store.setContents(fList);
store.commit();
} catch (Exception e) {
retVal = false;
}
return retVal;
}}
The entry poing is following:
public class SyncItemSample extends UiApplication {
private static PersistentObject store;
private static UserList userList;
static {
store = PersistentStore.getPersistentObject(0x3167239af4aa40fL);
}
public static void main(String[] args) {
SyncItemSample app = new SyncItemSample();
app.enterEventDispatcher();
}
public SyncItemSample() {
UserListScreen userListScreen;
//Check to see if the store exists on the BlackBerry.
synchronized (store) {
if (store.getContents() == null) {
//Store does not exist, create it with default values
userList = new UserList();
store.setContents(userList);
store.commit();
} else {
//Store exists, retrieve data from store.
userList = (UserList)store.getContents();
}
}
//Create and push the UserListScreen.
userListScreen = new UserListScreen(userList);
pushScreen(userListScreen);
}}
And here is an implementation of screen:
public final class UserListScreen extends MainScreen {
Vector fLabels = new Vector();
Vector fValues = new Vector();
VerticalFieldManager leftColumn = new VerticalFieldManager();
VerticalFieldManager rightColumn = new VerticalFieldManager();
UserList fList;
public UserListScreen(UserList list) {
super();
fList = list;
//Create a horizontal field manager to hold the two vertical field
//managers to display the names and ages in two columns.
VerticalFieldManager inputManager = new VerticalFieldManager();
HorizontalFieldManager backGround = new HorizontalFieldManager();
//Array of fields to display the names and ages.
LabelField title = new LabelField("User List",
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
setTitle(title);
final TextField fld1 = new TextField(TextField.NO_NEWLINE);
fld1.setLabel("input label");
inputManager.add(fld1);
final TextField fld2 = new TextField(TextField.NO_NEWLINE);
fld2.setLabel("input value");
inputManager.add(fld2);
final ButtonField fld3 = new ButtonField();
fld3.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
fList.getData().put(fld1.getText().trim(), fld2.getText().trim());
refresh();
}
});
fld3.setLabel("add");
inputManager.add(fld3);
add(inputManager);
//Add the column titles and a blank field to create a space.
LabelField leftTitle = new LabelField("label ");
leftColumn.add(leftTitle);
LabelField rightTitle = new LabelField("value");
rightColumn.add(rightTitle);
refresh();
//Add the two vertical columns to the horizontal field manager.
backGround.add(leftColumn);
backGround.add(rightColumn);
//Add the horizontal field manager to the screen.
add(backGround);
}
private void refresh() {
leftColumn.deleteAll();
rightColumn.deleteAll();
fLabels.removeAllElements();
fValues.removeAllElements();
//Populate and add the name and age fields.
Enumeration e = fList.getData().keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) fList.getData().get(key);
final LabelField tmp1 = new LabelField(key);
final LabelField tmp2 = new LabelField(value);
leftColumn.add(tmp1);
rightColumn.add(tmp2);
fLabels.addElement(tmp1);
fValues.addElement(tmp2);
}
}
public boolean onClose() {
System.exit(0);
return true;
}}
So as you see it should be very easy...
So all of these I run application, add values to Persistent object and they are added correctly, are stored during device resets and so on...
When I run Desktop Manager and make a Backup it seems that UserList is backed-up, as size of backup grows together with adding new data into persistent store.
But when I run "Wipe device" on my BB 9300 (and all data from Persistent store is cleared as it is expected) and then run Restore from just made backup file - nothing is updated in the Application and persistent store is seems to be empty.
In some examples I have found adding alternate entry point "init" but I can't tune eveything like it is described with my EclipsePlugin
Could you advice me how to store data in backup file and the to retrieve the same data from backup and load it back to the application, or how to log any of events with Desktop Manager?
If someone has experienced the same problem you can try to disconnect the device before wiping it. It is strange but it helped :)

Blackberry - How to get the background application process id

In my blackberry simulator i m running two application at the background now i want to retrive which are the application running in the background.I don't how to do. Is it possible to show which are the application running in the background.
List and switch visible application
To list all visible applications use ApplicationManager.getVisibleApplications()
To bring some application foreground use ApplicationManager.requestForeground(processId)
alt text http://img195.imageshack.us/img195/7003/applist.png link text http://img32.imageshack.us/img32/9273/applistmenu.png
Code:
class Scr extends MainScreen {
ApplicationDescriptor[] mAppDes;
public Scr() {
listApplications();
}
void listApplications() {
ApplicationManager appMan =
ApplicationManager.getApplicationManager();
mAppDes = appMan.getVisibleApplications();
add(new LabelField("Visible Applications:"));
for (int i = 0; i < mAppDes.length; i++) {
boolean isFG = appMan.getProcessId(mAppDes[i]) == appMan
.getForegroundProcessId();
String text = (isFG ? "[F]:" : "[B]") + mAppDes[i].getName();
add(new LabelField(text));
}
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(refreshApps);
makeAppMenuItems(menu);
}
MenuItem refreshApps = new MenuItem("Refresh", 0, 0) {
public void run() {
deleteAll();
listApplications();
}
};
class AppMenuItem extends MenuItem {
ApplicationDescriptor mAppDes;
public AppMenuItem(ApplicationDescriptor appDes) {
super(appDes.getName(), 100000, 100000);
mAppDes = appDes;
}
public void run() {
ApplicationManager appMan = ApplicationManager
.getApplicationManager();
int processId = appMan.getProcessId(mAppDes);
appMan.requestForeground(processId);
}
}
void makeAppMenuItems(Menu menu) {
for (int i = 0, cnt = mAppDes.length; i < cnt; i++)
menu.add(new AppMenuItem(mAppDes[i]));
}
}
Take a look at the API Reference for the RuntimeStore.
And a Knowledge Base entry how to switch an App to the Background/Foreground.
Good Luck!
Not really an answer, but the system won't let me comment.
Do you really need to know what the running background applications are, or just if your applications are running in the background. If the latter I imagine you can build something using the runtime store

BlackBerry - Simulate a KeyPress event

I have a BlackBerry application that needs to take pictures from the camera and send them to a server. In order to do this i invoke the native camera application and listen to the filesystem. Once an image is captured and saved as a new jpeg file i get notified, resume foreground control and go about my business. The problem starts occurring after the first time this cycle is completed because now when i decide to call the camera application again it is already opened, and now the user is seeing a thumbnail of the last picture that was taken and several buttons allowing him to manipulate/manage it. naturally what i want the user to see is a preview of what the camera is "seeing" before he snaps another photo as he did before.
I have thought of various ways to solve this including killing the camera app each time (I understand this cannot be done programatically?), sending CameraArguments when invoking the app (which appears to be useless), and now i was thinking a solution could be as simple generating a "Back" key event before switching back to my app which would theoretically dismiss the annoying edit screen. Could this really be done? and if not is there any other possible solution you may think of?
A kind of hack...
start Camera App
in TimerTask check if Camera App started and if it need to be closed (some flag)
if yes, invoke it(so it will became active) and push ESC keypress event injection to close it
Take a look at this:
class Scr extends MainScreen {
boolean killCameraApp = false;
final String mCameraModuleName = "net_rim_bb_camera";
final CameraArguments args = new CameraArguments();
public Scr() {
super();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (isCameraRunning() && killCameraApp) {
getApplication().invokeAndWait(callCamera);
getApplication().invokeAndWait(killCamera);
}
}
}, 0, 100);
}
Runnable callCamera = new Runnable() {
public void run() {
callCamera();
}
};
Runnable killCamera = new Runnable() {
public void run() {
injectKey(Characters.ESCAPE);
killCameraApp = false;
}
};
private boolean isCameraRunning() {
boolean result = false;
ApplicationManager appMan =
ApplicationManager.getApplicationManager();
ApplicationDescriptor[] appDes = appMan.getVisibleApplications();
for (int i = 0; i < appDes.length; i++) {
result = mCameraModuleName.equalsIgnoreCase(appDes[i]
.getModuleName());
if (result)
break;
}
return result;
}
private void callCamera() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
private void injectKey(char key) {
KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, key, 0);
inject.post();
}
protected void makeMenu(Menu menu, int instance) {
menu.add(new MenuItem("start camera", 0, 0) {
public void run() {
callCamera();
killCameraApp = false;
}
});
menu.add(new MenuItem("kill app", 0, 0) {
public void run() {
killCameraApp = true;
}
});
super.makeMenu(menu, instance);
}
}
EDIT: Don't forget to set permissions for device release:
Options => Advanced Options => Applications => [Your Application] =>Edit Default permissions =>Interactions =>key stroke Injection

Resources