Can any one provide me with a working example of JNA mouse hook, which would be able to track mouse movements/click outside my Java Swing application ?
Thanks in Advance
Yep, here is the code...
public class CWMouseHook {
public final User32 USER32INST;
public final Kernel32 KERNEL32INST;
public CWMouseHook()
{
if(!Platform.isWindows())
{
throw new UnsupportedOperationException("Not supported on this platform.");
}
USER32INST = User32.INSTANCE;
KERNEL32INST = Kernel32.INSTANCE;
mouseHook=hookTheMouse();
Native.setProtected(true);
}
public static LowLevelMouseProc mouseHook;
public HHOOK hhk;
public Thread thrd;
public boolean threadFinish = true;
public boolean isHooked = false;
public static final int WM_MOUSEMOVE = 512;
public static final int WM_LBUTTONDOWN = 513;
public static final int WM_LBUTTONUP = 514;
public static final int WM_RBUTTONDOWN = 516;
public static final int WM_RBUTTONUP = 517;
public static final int WM_MBUTTONDOWN = 519;
public static final int WM_MBUTTONUP = 520;
public void unsetMouseHook()
{
threadFinish = true;
if (thrd.isAlive())
{
thrd.interrupt();
thrd = null;
}
isHooked = false;
}
public boolean isIsHooked()
{
return isHooked;
}
public void setMouseHook()
{
thrd = new Thread(new Runnable() {
#Override
public void run()
{
try
{
if(!isHooked)
{
hhk = USER32INST.SetWindowsHookEx(14, mouseHook,KERNEL32INST.GetModuleHandle(null),0);
isHooked = true;
MSG msg = new MSG();
while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0)
{
USER32INST.TranslateMessage(msg);
USER32INST.DispatchMessage(msg);
System.out.print(isHooked);
if (!isHooked)
break;
}
}
else
System.out.println("The Hook is already installed.");
}
catch (Exception e)
{ System.err.println(e.getMessage());
System.err.println("Caught exception in MouseHook!");
}
}
},"Named thread");
threadFinish = false;
thrd.start();
}
private interface LowLevelMouseProc extends HOOKPROC
{
LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);
}
public LowLevelMouseProc hookTheMouse() {
return new LowLevelMouseProc()
{
#Override
public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) {
if (nCode >= 0)
{
switch(wParam.intValue())
{
case CWMouseHook.WM_LBUTTONDOWN:
// do stuff
break;
case CWMouseHook.WM_RBUTTONDOWN:
//do stuff
break;
case CWMouseHook.WM_MBUTTONDOWN:
//do other stuff
break;
case CWMouseHook.WM_LBUTTONUP:
//do even more stuff
break;
case CWMouseHook.WM_MOUSEMOVE:
break;
default:
break;
}
/****************************DO NOT CHANGE, this code unhooks mouse *********************************/
if (threadFinish == true)
{
USER32INST.PostQuitMessage(0);
}
/***************************END OF UNCHANGABLE *******************************************************/
}
return USER32INST.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
}
public class Point extends Structure
{
public class ByReference extends Point implements Structure.ByReference {};
public NativeLong x;
public NativeLong y;
}
public static class MOUSEHOOKSTRUCT extends Structure
{
public static class ByReference extends MOUSEHOOKSTRUCT implements Structure.ByReference {};
public POINT pt;
public HWND hwnd;
public int wHitTestCode;
public ULONG_PTR dwExtraInfo;
}
That's all about there is to it. Cheers.
It's a basically a ripoff of the code of a guy in Sun forums...but also tested by me, and it works so cheers again.
Edit: I edited the code so it includes the LowLevelMouseProc but you can use your extension of HOOK which you can define elsewhere. It doesn't matter that much. Be wary that for some reason you have TO have the variable mouseHook as static otherwise hook just unhooks after a while.
movements:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;
public class GlobalMouseWheelListenerExample implements NativeMouseWheelListener {
public void nativeMouseWheelMoved(NativeMouseWheelEvent e) {
System.out.println("Mosue Wheel Moved: " + e.getWheelRotation());
}
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
// Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeMouseWheelListener(new GlobalMouseWheelListenerExample());
}
}
click:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
public class GlobalMouseListenerExample implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
System.out.println("Mosue Clicked: " + e.getClickCount());
}
public void nativeMousePressed(NativeMouseEvent e) {
System.out.println("Mosue Pressed: " + e.getButton());
}
public void nativeMouseReleased(NativeMouseEvent e) {
System.out.println("Mosue Released: " + e.getButton());
}
public void nativeMouseMoved(NativeMouseEvent e) {
System.out.println("Mosue Moved: " + e.getX() + ", " + e.getY());
}
public void nativeMouseDragged(NativeMouseEvent e) {
System.out.println("Mosue Dragged: " + e.getX() + ", " + e.getY());
}
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
//Construct the example object.
GlobalMouseListenerExample example = new GlobalMouseListenerExample();
//Add the appropriate listeners for the example object.
GlobalScreen.getInstance().addNativeMouseListener(example);
GlobalScreen.getInstance().addNativeMouseMotionListener(example);
}
}
Related
I am learning Java and have encountered an unexpected problem:
variable i is getting updated in mouse listener but updated value is not getting passed back to main program. But if I uncomment Thread.sleep(1) block everything is back to normal.
Here is the program:
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends Frame
implements MouseListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
static int i=0;//State variable
public MouseEventDemo()
{
addMouseListener(this);
addWindowListener(new MyWindowAdapter());
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
i=1;
msg = "Click received. i= "+i;
mouseX = me.getX();
mouseY = me.getY();
repaint();
}
public void mouseMoved(MouseEvent me)
{
}
public void mouseDragged(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
// Display msg in the window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
public static void main(String[] args)
{
MouseEventDemo appwin = new MouseEventDemo();
appwin.setSize(new Dimension(300, 300));
appwin.setTitle("MouseEventDemo");
appwin.setVisible(true);
while (true)
{
if(i==1)
{
System.out.println("Value of i is: "+i);
i=0;
}
/*
try
{
Thread.sleep(1);
}
catch(Exception e)
{
System.out.println(e);
};
*/
}
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
This program behaves not like I have expected, but with Thread.sleep(1) it changes it behaviour
I have a AutoCompleteTextView that I give it 2 different adapters depending on the amount of text that is being present at the textview - if it has 0 characters I want it to display a list of "recently searched" strings adapter, while if it has more than 1 characters I want it to display auto completion list.
My getRecentlySearchedQueries method along with the RecentSearchedViewModel-
private List<String> recentlySearchedQueries = new ArrayList<>(); // pasted from the top of the class
#Override
public void getRecentlySearchedQueries() {
recentSearchViewModel.getAllQueries().observe(getActivity(), databaseRecentlySearchList -> {
if (databaseRecentlySearchList == null) {
return;
}
for (int i = 0; i < databaseRecentlySearchList.size(); i++) {
Log.d("localDBValue", "Added value - " + databaseRecentlySearchList.get(i).toString() + "\n");
String query = databaseRecentlySearchList.get(i).getQuery();
recentlySearchedQueries.add(query);
}
//Log.d("localDBValue", "recent search list value - " + recentlySearchedQueries);
});
}
public class RecentSearchViewModel extends AndroidViewModel {
private RecentSearchRepository recentSearchRepository;
private LiveData<List<RecentSearchModel>> allRecentlySearched;
public RecentSearchViewModel(#NonNull Application application) {
super(application);
recentSearchRepository = new RecentSearchRepository(application);
allRecentlySearched = recentSearchRepository.getAllRecentSearches();
}
public void insert(RecentSearchModel model) {
recentSearchRepository.insert(model);
}
public void update(RecentSearchModel model) {
// add implementation in the future if needed
}
public void delete(RecentSearchModel model) {
// add implementation in the future if needed
}
public LiveData<List<RecentSearchModel>> getAllQueries() {
return allRecentlySearched;
}
}
public class RecentSearchRepository {
private RecentSearchDao recentSearchDao;
private LiveData<List<RecentSearchModel>> allRecentSearches;
public RecentSearchRepository(Application application) {
MarketplaceDatabase database = MarketplaceDatabase.getRecentSearchInstance(application);
recentSearchDao = database.recentSearchDao();
allRecentSearches = recentSearchDao.getRecentSearchList();
}
public void insert(RecentSearchModel model) {
new RecentSearchRepository.InsertRecentSearchAsyncTask(recentSearchDao).execute(model);
}
public void update (RecentSearchModel model) {
//TODO - implement in future if needed
}
public void delete(RecentSearchModel model) {
//TODO - implement in future if needed
}
public LiveData<List<RecentSearchModel>> getAllRecentSearches() {
return allRecentSearches;
}
private static class InsertRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public InsertRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.insert(recentSearchModels[0]);
return null;
}
}
private static class UpdateRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public UpdateRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.update(recentSearchModels[0]);
return null;
}
}
}
#Dao
public interface RecentSearchDao {
#Insert()
void insert(RecentSearchModel model);
#Update
void update(RecentSearchModel model);
#Delete
void delete(RecentSearchModel model);
#Query("select * from recent_search_table")
LiveData<List<RecentSearchModel>> getRecentSearchList();
}
#Entity(tableName = "recent_search_table")
public class RecentSearchModel {
#PrimaryKey(autoGenerate = true)
private int ID;
private String query;
public RecentSearchModel(){
}
public RecentSearchModel(String query) {
this.query = query;
}
public void setID(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
#Override
public String toString() {
return "RecentSearchModel{" +
"query='" + query + '\'' +
'}';
}
#Override
public boolean equals(#Nullable Object obj) {
if (obj instanceof RecentSearchModel)
return this.query.equalsIgnoreCase(((RecentSearchModel) obj).query);
return false;
}
}
So, what I am doing here is for start getting all values inside my local DB and adding them to my String list that is part of the adapter. So far so good.
The issue I am facing is that the adapter won't show the amount of strings available in the list that populates it. In fact, it sometimes shows a view half-cut with wierd information, sometimes does not show anything and sometimes shows part of the corrent information. What am I missing?
Another thing I am facing is that the "recently searched" adapter won't work when clicking on the AutoCompleteTextView - it only works when typing and deleting values so the char length is 0. How can I make it work from start of focus?
Here is the way I am populating the information to the ViewModel -
/**
* Shows the searched products following
*/
#Override
public void getSearchedProducts(String searchedQuery) {
MarketplaceUtils.getSearchedProducts(searchedQuery, marketApiCalls, false, initialSearchTake, initialMarketplacePage, new MarketplaceUtils.OnProductsFetchCompleteListener() {
#Override
public void onSuccess(List<MiniProductModel> list) {
if (!searchedQuery.equals(currentSearchedText))
return;
if (list == null) {
//reaching here means we do not have a result to show to the UI so we empty the list.
currentProductList.clear();
productsAdapter.notifyDataSetChanged();
return;
}
if (searchedQuery.length() > 3 && searchAutoCompleteStrings.contains(searchedQuery)) {
Log.d("localDBValue", "searchedValue - " + searchedQuery);
recentSearchViewModel.insert(new RecentSearchModel(searchedQuery));
}
mPresenter.setDiscoverProductsLayoutVisibility(View.GONE);
currentProductList.clear();
currentProductList.addAll(list);
productsAdapter.notifyDataSetChanged();
}
#Override
public void onError(Throwable throwable) {
Log.d("searchedProducts", throwable.getMessage());
}
});
}
The default behaviour for #Insert method of Room is OnConflictStrategy.ABORT - so what I did is to implement equals() method to verify that the RecentSearchModels that are being compared are compared by their string value. Still does seems to effect anything.
Outgoing calls are ended automatically when phonestatelistener is used to monitor the calls.
This is my code and when this is executed it blocks the outgoing calls :
public class CallHelper {
public String number;
private Context ctx;
private TelephonyManager tm;
private CallStateListener callStateListener;
private OutgoingReceiver outgoingReceiver;
SharedPreferences trackMeData;
public CallHelper(Context ctx) {
this.ctx = ctx;
number ="";
callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
trackMeData = ctx.getSharedPreferences("LockedSIM", 0);
}
private class CallStateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
number = incomingNumber;
sendsmstoph(number);
System.out.println("Incomgin");
Toast.makeText(ctx, "Incoming: " + incomingNumber,Toast.LENGTH_LONG).show();
break;
}
}
}
public class OutgoingReceiver extends BroadcastReceiver {
public OutgoingReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(ctx, "Outgoing: " + number, Toast.LENGTH_LONG).show();
sendsmstoph(number);
}
}
I have developed the demo application of blackberry analytic service but report is not updated in my account my program is..
public class MyApp extends WebtrendsUiApplication {
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
WebtrendsConfigurator.LoadConfigFile(new AnalyticsConfig());
WebtrendsDataCollector wtDC = WebtrendsDataCollector.getInstance();
wtDC.Initialize();
pushScreen(new MyScreen());
}
private class AnalyticsConfig extends WebtrendsConfig {
public String wt_dc_app_name() {
return "sample";
}
public String wt_dc_app_version() {
return "1.0.1";
}
public String wt_dc_dcsid() {
return "dcswcrmlj9dv0hgctfq9y6lw8_3w4g"; // Analytics Demo
}
public String wt_dc_debug() {
return "true";
}
public String wt_dc_timezone() {
return "+5";
}
public String wt_dc_url() {
return "http://dc.webtrends.com/v1";
}
public String wt_dc_app_category() {
return "Utilities";
}
public String wt_dc_app_publisher() {
return "abc";
}
}
}
public final class MyScreen extends MainScreen implements FieldChangeListener{
ButtonField b;
public MyScreen() {
b=new ButtonField();
b.setChangeListener(this);
add(b);
}
public boolean onClose() {
try {
WebtrendsDataCollector.getInstance().onApplicationTerminate("Application Terminate", null);
} catch (IllegalWebtrendsParameterValueException err) {
WebtrendsDataCollector.getLog().e(err.getMessage());
}
System.exit(0);
return true;
}
public void fieldChanged(Field field, int context) {
if(field==b){
try {
WebtrendsDataCollector.getInstance().onAdClickEvent("/mainscreen", "Main Screen", "menu", null, "Demo Ad");
} catch (IllegalWebtrendsParameterValueException e1) {
System.out.println(e1.toString());
e1.printStackTrace();
}
}
}
}
please find where is the problem. I have changed only the dcsid in the application .
I know this question is quite old..but I wrote like a group of class u can use.. https://bitbucket.org/folorunsho1/googleanalyticsforblackberry
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);
}
}