Dispatchevent not working in native extension for ios - addeventlistener

I've build a native extension for my project to fire two event about login and logout,this is code (NdPlatformExtension.as), the extIntance for singleton have tried but get same result,so ignore it.
private static const API_LOGIN_CALL:String = "LogIn";
private static const API_LOGOUT_CALL:String = "LogOut";
private static const EXTENSION_ID:String = "NdPlatformExt";
public var extContext:ExtensionContext;
private static var extIntance:NdPlatformExtension = null;
public function NdPlatformExtension()
{
extContext = ExtensionContext.createExtensionContext(EXTENSION_ID,"");
extContext.addEventListener(StatusEvent.STATUS,onEvent);
}
public static function get ExtInstance():NdPlatformExtension {
if(extIntance == null) {
extIntance = new NdPlatformExtension();
}
return extIntance;
}
public function onEvent(e:StatusEvent):void {
ConsoleLog(e.code);
switch(e.code)
{
case NdPlatformEvent.EVENT_API_LOGIN_RESULT:
{
ConsoleLog("event dispatch start");
var _succed:Boolean = dispatchEvent(new NdPlatformEvent(NdPlatformEvent.EVENT_API_LOGIN_RESULT,e.level.split('|')));
_succed = dispatchEvent(new NdPlatformEvent(NdPlatformEvent.EVENT_API_TEST,null));
ConsoleLog(_succed);//i've been checked on the log the _succed is true
}
break;
default:
{
dispatchEvent(new NdPlatformEvent(NdPlatformEvent.EVENT_API_LOGIN_RESULT,null));
}
break;
}
}
public function LogIn():String {
var _result:String = "";
try
{
_result = extContext.call(API_LOGIN_CALL) as String;
}
catch(_e:Error)
{
_result = _e.message;
}
return _result;
}
public function LogOut():String {
var _result:String = "";
try
{
_result = extContext.call(API_LOGOUT_CALL) as String;
}
catch(_e:Error)
{
_result = _e.message;
}
return _result;
}
}
}
And build a test flex project to listen the custom events, but all listeners I added are not fire. Here the view file content,the listener will add in view creationComplete.
...creationComplete="init()" title="Test">
<fx:Script>
<![CDATA[
import NdPlatformExt.NdPlatformEvent;
import NdPlatformExt.NdPlatformExtension;
import flash.events.Event;
private var ext:NdPlatformExtension = new NdPlatformExtension();
protected function button1_clickHandler(event:MouseEvent):void
{
ext.LogIn();
}
protected function button2_clickHandler(event:MouseEvent):void
{
}
public function init():void
{
ext.addEventListener(NdPlatformEvent.EVENT_API_LOGIN_RESULT,onLoginResult,true);
ext.addEventListener(NdPlatformEvent.EVENT_API_TEST,onTest,true);
}
public function onLoginResult(_event:NdPlatformEvent):void{
ext.ConsoleLog("event receive ok");
ext.LogOut();
}
public function onTest():void{
ext.ConsoleLog("test receive ok");
}
]]>
</fx:Script>
<fx:Declarations>
</fx:Declarations>
<s:Label id="output" x="14" y="70" width="300" height="32" text=""/>
<s:Button x="44" y="19" width="231" label="Login"
click="button1_clickHandler(event)" alignmentBaseline="ideographicCenter"/>
<s:Button x="44" y="111" width="231" label="Purchase"
click="button2_clickHandler(event)" alignmentBaseline="ideographicCenter"/>
but all listener i added are not fire.

Related

Navigation On Universal Windows platform

I am developing a Windows Universal App which is hosting a web app using webview.
steps are followed as like.
Creating a Blank universal window app. Creating a Splash screen. Set
splash screen as starting page. After all activity i would like to
navigate the Main page which is having a web view control.
Setting a url example "http:www.google.come" as source for the web view. everything it works a fine but the main page takes time, where i would like to see the same splash screen till it loads.
Code for Navigation i am using
this.Frame.Navigate(typeof(MainPage));
full source code
public sealed partial class ExtentedSpash : Page
{
public ProgressMessage Progress;
public ExtentedSpash()
{
this.InitializeComponent();
Progress = ProgressMessage.GetMessage();
DataContext = Progress;
Window.Current.Activate();
Loaded += Splash_Loaded;
}
private async void Splash_Loaded(object sender, RoutedEventArgs e)
{
await Initialize();
Window.Current.Activate();
await ClearBrowserCache();
Window.Current.Activate();
//Task.WaitAll(TaskList.ToArray());
await StartApplication();
}
public async Task Initialize()
{
Progress.ActionMessage = "Initialize the controls";
await Task.Delay(TimeSpan.FromSeconds(10));
}
public async Task ClearBrowserCache()
{
Progress.ActionMessage = "Clear Browser Cache";
await Task.Delay(TimeSpan.FromSeconds(10));
}
public async Task StartApplication()
{
Progress.ActionMessage = "Loading";
await Task.Delay(TimeSpan.FromSeconds(10));
this.Frame.Navigate(typeof(MainPage));
}
private void btnMain_Click(object sender, RoutedEventArgs e)
{
}
}
public class ProgressMessage : INotifyPropertyChanged
{
private string statusMessage;
public string StatusMessage
{
get { return statusMessage; }
set
{
statusMessage = value;
RaiseProperChanged();
}
}
private string actionMessage;
public string ActionMessage
{
get { return actionMessage; }
set
{
actionMessage = value;
RaiseProperChanged();
}
}
private bool showProgress;
public bool ShowProgress
{
get { return showProgress; }
set { showProgress = value;
RaiseProperChanged();
}
}
public static ProgressMessage GetMessage()
{
var msg = new ProgressMessage()
{
StatusMessage = "Initializing Application",
ActionMessage = "One moment please...",
showProgress = true
};
return msg;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaiseProperChanged(
[CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}
}
I want "On Loading" message should show til it fully loads the application.
As we've discussed, if you just want to cover the WebView when it's source is not complete loaded, you can do it like this:
<Page.Resources>
<Storyboard x:Key="MyTextSTD" x:Name="MyTextSTD" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="tbbrush" Storyboard.TargetProperty="Color" Duration="0:0:10">
<DiscreteColorKeyFrame KeyTime="0:0:0" Value="Red" />
<LinearColorKeyFrame KeyTime="0:0:5" Value="Blue" />
<LinearColorKeyFrame KeyTime="0:0:10" Value="Purple" />
</ColorAnimationUsingKeyFrames>
</Storyboard>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView Source="https://msdn.microsoft.com/library/windows/apps/xaml/mt244352.aspx" NavigationCompleted="WebView_NavigationCompleted">
</WebView>
<Grid x:Name="loadingGrid" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Visibility="Visible">
<TextBlock Text="On Loading..." FontSize="50" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock.Foreground>
<SolidColorBrush x:Name="tbbrush" />
</TextBlock.Foreground>
</TextBlock>
</Grid>
</Grid>
And code behind:
public MainPage()
{
this.InitializeComponent();
MyTextSTD.Begin();
}
private void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
loadingGrid.Visibility = Visibility.Collapsed;
}
Here is quite simple, I use a TextBlock and some color animation to show the message. And this message will disappear when the source of WebView is fully loaded.

Where can I find the source code for ActivityTestRule?

Where can I find the source code for ActivityTestRule?
You can find it at
https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/rules/src/main/java/android/support/test/rule/ActivityTestRule.java
You have to use branch android-support-test instead of master on platform/frameworks/testing project in AOSP.
You can add ActivityTestRule in code, import library and CTRL+Left Click to decompile.
If you can't import this class, you need to add it to dependencies in your build.gradle
androidTestCompile 'com.android.support.test:rules:0.3'
EDIT:
My result of decompiling:
package android.support.test.rule;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.Beta;
import android.support.test.internal.util.Checks;
import android.support.test.rule.UiThreadTestRule;
import android.util.Log;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
#Beta
public class ActivityTestRule<T extends Activity> extends UiThreadTestRule {
private static final String TAG = "ActivityInstrumentationRule";
private final Class<T> mActivityClass;
private Instrumentation mInstrumentation;
private boolean mInitialTouchMode;
private boolean mLaunchActivity;
private T mActivity;
public ActivityTestRule(Class<T> activityClass) {
this(activityClass, false);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode) {
this(activityClass, initialTouchMode, true);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode, boolean launchActivity) {
this.mInitialTouchMode = false;
this.mLaunchActivity = false;
this.mActivityClass = activityClass;
this.mInitialTouchMode = initialTouchMode;
this.mLaunchActivity = launchActivity;
this.mInstrumentation = InstrumentationRegistry.getInstrumentation();
}
protected Intent getActivityIntent() {
return new Intent("android.intent.action.MAIN");
}
protected void beforeActivityLaunched() {
}
protected void afterActivityLaunched() {
}
protected void afterActivityFinished() {
}
public T getActivity() {
if(this.mActivity == null) {
Log.w("ActivityInstrumentationRule", "Activity wasn\'t created yet");
}
return this.mActivity;
}
public Statement apply(Statement base, Description description) {
return new ActivityTestRule.ActivityStatement(super.apply(base, description));
}
public T launchActivity(#Nullable Intent startIntent) {
this.mInstrumentation.setInTouchMode(this.mInitialTouchMode);
String targetPackage = this.mInstrumentation.getTargetContext().getPackageName();
if(null == startIntent) {
startIntent = this.getActivityIntent();
if(null == startIntent) {
Log.w("ActivityInstrumentationRule", "getActivityIntent() returned null using default: Intent(Intent.ACTION_MAIN)");
startIntent = new Intent("android.intent.action.MAIN");
}
}
startIntent.setClassName(targetPackage, this.mActivityClass.getName());
startIntent.addFlags(268435456);
Log.d("ActivityInstrumentationRule", String.format("Launching activity %s", new Object[]{this.mActivityClass.getName()}));
this.beforeActivityLaunched();
this.mActivity = (Activity)this.mActivityClass.cast(this.mInstrumentation.startActivitySync(startIntent));
this.mInstrumentation.waitForIdleSync();
this.afterActivityLaunched();
return this.mActivity;
}
void setInstrumentation(Instrumentation instrumentation) {
this.mInstrumentation = (Instrumentation)Checks.checkNotNull(instrumentation, "instrumentation cannot be null!");
}
void finishActivity() {
if(this.mActivity != null) {
this.mActivity.finish();
this.mActivity = null;
}
}
private class ActivityStatement extends Statement {
private final Statement mBase;
public ActivityStatement(Statement base) {
this.mBase = base;
}
public void evaluate() throws Throwable {
try {
if(ActivityTestRule.this.mLaunchActivity) {
ActivityTestRule.this.mActivity = ActivityTestRule.this.launchActivity(ActivityTestRule.this.getActivityIntent());
}
this.mBase.evaluate();
} finally {
ActivityTestRule.this.finishActivity();
ActivityTestRule.this.afterActivityFinished();
}
}
}
}

How to filter lookup values on a dialogfield in Report Dialog based on another dialogfield in AX 2012 AOT reports?

How can i implement Customized lookup in Report Dialog box.
for example i have two fields in my report dialog 1) Custgroup 2) CustAccount
if i have selected a particuler cust group in first field then second field lookup should show only customers those come under this cust groups.
//class
public class ReportRun extends ObjectRun
{
DialogField dialogcustGroup,dialogcustaccount ;
CustTable obj_CustTable ;
}
//dialog method
public Object dialog(Object _dialog)
{
DialogRunbase dialog = _dialog;
DialogGroup toFromGroup;
Args _args;
str accountnum,custGroup;
;
// _args = new Args();
// obj_dev_CustTable = _args.record();
//accountnum = obj_dev_CustTable.AccountNum;
dialogcustGroup = dialog.addFieldValue(extendedTypeStr(CustGroup),CustGroup,"");
while select obj_CustTable
where obj_CustTable.AccountNum == dialogcustGroup .value()
{
CID = obj_dev_CustTable.CID;
dialogcustaccount =dialog.addFieldValue(ExtendedTypeStr(AccountNum),accountnum,"CID");
}
return dialog;
}
Any help would be great!!!!
The best way to do it is to override the lookup() method on the specified DialogField. See the example below - it works just fine.
class CustomizedLookup extends RunBase
{
DialogRunbase dialog;
DialogField dFieldCustGroup;
DialogField dFieldCustAccount;
CustGroupId fetchedCustGroup;
CustAccount fetchedAccountNum;
}
protected Object dialog()
{
dialog = super();
FieldCustGroup = dialog.addField(extendedTypeStr(CustGroupId),"sysLabel1");
dFieldCustGroup.allowEdit(true);
dFieldCustAccount = dialog.addField(extendedTypeStr(CustAccount),"sysLabel1");
dFieldCustAccount.allowEdit(false);
return dialog;
}
public void dialogPostRun(DialogRunbase _dialog)
{
super(_dialog);
// allow to call the event methods
// of this class (e.g. Fld1_1_modified() method)
_dialog.dialogForm().formRun().controlMethodOverload(true);
_dialog.dialogForm().formRun().controlMethodOverloadObject(this);
}
private boolean Fld1_1_modified() // dFieldCustGroup
{
FormStringControl control;
boolean isFieldModified;
control = dialog.formRun().controlCallingMethod();
isFieldModified = control.modified();
if(isFieldModified)
{
fetchedCustGroup = dFieldCustGroup.value();
dFieldCustAccount.allowEdit(true);
}
return isFieldModified;
}
private void Fld2_1_lookup() //dFieldCustAccount
{
FormStringControl control = dialog.formRun().controlCallingMethod();
SysTableLookup sysTableLookup = SysTableLookup::newParameters(tablenum(CustTable),control);
Query query = new Query();
QueryBuildDataSource queryBuildDataSource;
QueryBuildRange queryBuildRange;
queryBuildDataSource = query.addDataSource(TableNum(CustTable));
queryBuildRange = queryBuildDataSource.addRange(FieldNum(CustTable, CustGroup));
queryBuildRange.value(fetchedCustGroup);
sysTableLookup.addLookupfield(fieldnum(CustTable, AccountNum));
sysTableLookup.addLookupfield(fieldnum(CustTable, CustGroup));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
public boolean getFromDialog()
{
boolean ret;
ret = super();
fetchedAccountNum = dFieldCustAccount.value();
return ret;
}
static void main(Args _e)
{
CustomizedLookup customizedLookup;
customizedLookup = new CustomizedLookup();
if (customizedLookup.prompt())
{
customizedLookup.run();
// do some actions with your data
customizedLookup.theAction();
}
}
private void theAction()
{
info(strFmt("Customer Group: %1",fetchedCustGroup));
info(strFmt("Account Number: %1",fetchedAccountNum));
}
Some more methods like pack , unpack and main method should be declared
public class CustAmountCalculation extends RunBase
{
DialogField fieldAccount;
CustAccount custAccount;
}
public Object dialog()
{
Dialog dialog;
DialogGroup groupCustomer;
dialog = super();
fieldAccount = dialog.addField(extendedTypeStr(custAccount), "CustomerAccount");
return dialog;
}
public boolean getFromDialog()
{
custAccount = fieldAccount.value();
return super();
}
public container pack()
{
return conNull();
}
public void run()
{
CustTable custTable;
CustTrans custTrans;
;
select sum(AmountMST) from custTrans where custTrans.AccountNum == custAccount;
info("You have enetered customer information");
info(strfmt("Account: %1", custAccount));
info(strFmt("Amount: %1", custTrans.AmountMST));
}
public boolean unpack(container _packedClass)
{
return true;
}
public static void main(Args _args)
{
CustAmountCalculation custAmountCalculation = new CustAmountCalculation();
if (CustAmountCalculation.prompt())
{
CustAmountCalculation.run();
}
}

Air iOS SharedObject deleted after updating

I'm using SharedObjects in my game to store the progress of the player in the game (level scores, unlocked levels, etc.).
Everything is working fine, but the problem is when I submitted an update of the game (with the same certificates and the same names of the .swf and .ipa files) when the game is updated the old SharedObject is deleted and this is very big problem for the game and for me.
Both versions of the game are made with Flash CS 6 and Air SDK 3.5.
Any idea why the SharedObject is deleted, how can I prevent that?
I'm assuming that the reason why SharedObject becomes overwritten is because it's bundled with the .ipa during conversion.
I understand that will not help your current situation with salvaging your SharedObject but you could try using flash.filesystem to read/write your data to a preference file instead of employing SharedObject in the future.
Below is my Archive class that I use with my own work, but I've never developed for iOS before so i'm not certain that it will function as it does on other deployment targets, although I believe it should.
Use Case:
//Imports
import com.mattie.data.Archive;
import com.mattie.events.ArchiveEvent;
//Constants
private static const PREF_CANVAS_VOLUME:String = "prefCanvasVolume";
private static const DEFAULT_VOLUME:Number = 0.5;
//Initialize Archive
private function initArchive():void
{
archive = new Archive();
archive.addEventListener(ArchiveEvent.LOAD, init);
archive.load();
}
//Initialize
private function init(event:ArchiveEvent):void
{
archive.removeEventListener(ArchiveEvent.LOAD, init);
canvasVolume = archive.read(PREF_CANVAS_VOLUME, DEFAULT_VOLUME);
}
//Application Exiting Event Handler
private function applicationExitingEventHandler(event:Event):void
{
stage.nativeWindow.removeEventListener(Event.CLOSING, applicationExitingEventHandler);
archive.write(PREF_CANVAS_VOLUME, canvas.volume);
archive.addEventListener(ArchiveEvent.SAVE, archiveSavedEventHandler);
archive.save();
}
//Archive Saved Event Handler
private function archiveSavedEventHandler(event:ArchiveEvent):void
{
archive.removeEventListener(ArchiveEvent.SAVE, archiveSavedEventHandler);
NativeApplication.nativeApplication.exit();
}
Archive Class
package com.mattie.data
{
//Imports
import com.mattie.events.ArchiveEvent;
import flash.data.EncryptedLocalStore;
import flash.desktop.NativeApplication;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.registerClassAlias;
import flash.utils.ByteArray;
//Class
public final class Archive extends EventDispatcher
{
//Properties
private static var singleton:Archive;
//Variables
private var file:File;
private var data:Object;
//Constructor
public function Archive()
{
if (singleton)
{
throw new Error("Archive is a singleton that is only accessible via the \"archive\" public property.");
}
file = File.applicationStorageDirectory.resolvePath(NativeApplication.nativeApplication.applicationID + "Archive");
data = new Object();
registerClassAlias("Item", Item);
}
//Load
public function load():void
{
if (file.exists)
{
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
data = fileStream.readObject();
fileStream.close();
}
dispatchEvent(new ArchiveEvent(ArchiveEvent.LOAD));
}
//Read
public function read(key:String, defaultValue:* = null):*
{
var value:* = defaultValue;
if (data[key] != undefined)
{
var item:Item = Item(data[key]);
if (item.encrypted)
{
var bytes:ByteArray = EncryptedLocalStore.getItem(key);
if (bytes == null)
{
return value;
}
switch (item.value)
{
case "Boolean": value = bytes.readBoolean(); break;
case "int": value = bytes.readInt(); break;
case "uint": value = bytes.readUnsignedInt(); break;
case "Number": value = bytes.readDouble(); break;
case "ByteArray": bytes.readBytes(value = new ByteArray()); break;
default: value = bytes.readUTFBytes(bytes.length);
}
}
else
{
value = item.value;
}
}
return value;
}
//Write
public function write(key:String, value:*, encrypted:Boolean = false, autoSave:Boolean = false):void
{
var oldValue:* = read(key);
if (oldValue != value)
{
var item:Item = new Item();
item.encrypted = encrypted;
if (encrypted)
{
var constructorString:String = String(value.constructor);
constructorString = constructorString.substring(constructorString.lastIndexOf(" ") + 1, constructorString.length - 1);
item.value = constructorString;
var bytes:ByteArray = new ByteArray();
switch (value.constructor)
{
case Boolean: bytes.writeBoolean(value); break;
case int: bytes.writeInt(value); break;
case uint: bytes.writeUnsignedInt(value); break;
case Number: bytes.writeDouble(value); break;
case ByteArray: bytes.writeBytes(value); break;
default: bytes.writeUTFBytes(value);
}
EncryptedLocalStore.setItem(key, bytes);
}
else
{
item.value = value;
}
data[key] = item;
dispatchEvent(new ArchiveEvent(ArchiveEvent.WRITE, key, oldValue, value));
if (autoSave)
{
save();
}
}
}
//Remove
public function remove(key:String, autoSave:Boolean = false):void
{
if (data[key] != undefined)
{
var oldValue:* = read(key);
if (Item(data[key]).encrypted)
{
EncryptedLocalStore.removeItem(key);
}
delete data[key];
dispatchEvent(new ArchiveEvent(ArchiveEvent.DELETE, key, oldValue));
if (autoSave)
{
save();
}
}
}
//Contains
public function contains(key:String):Boolean
{
return (data[key] != undefined);
}
//Save
public function save():void
{
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeObject(data);
fileStream.close();
dispatchEvent(new ArchiveEvent(ArchiveEvent.SAVE));
}
//Get Singleton
public static function get archive():Archive
{
if (!singleton)
{
singleton = new Archive();
}
return singleton;
}
}
}
//Item
class Item
{
//Variables
public var value:*;
public var encrypted:Boolean = false;
}
Archive Event Class
package com.mattie.events
{
//Imports
import flash.events.Event;
//Class
public class ArchiveEvent extends Event
{
//Constants
public static const LOAD:String = "load";
public static const WRITE:String = "write";
public static const DELETE:String = "delete";
public static const SAVE:String = "save";
//Properties
public var key:String;
public var oldValue:*;
public var newValue:*;
//Constructor
public function ArchiveEvent(type:String, key:String = null, oldValue:* = null, newValue:* = null)
{
super(type);
this.key = key;
this.oldValue = oldValue;
this.newValue = newValue;
}
//Clone
public override function clone():Event
{
return new ArchiveEvent(type, key, oldValue, newValue);
}
//To String
public override function toString():String
{
return formatToString("ArchiveEvent", "type", "key", "oldValue", "newValue");
}
}
}

Get Camera captured images and create bitmap image

How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.
ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}
try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}

Resources