Android - taking pictures every minute with Camera - android-camera

I have a problem to solve - I was trying everything and nothing is working.
I am writing an application which should take picture every minute (period between pictures might be longer in future, but that isn't important) and upload it to ftp server. I am trying to open camera only for a while before taking photo and after taking photo release it and stop preview. But that doesn't work - there isn't even one picture taken. Opening camera etc. is doing by handler. If I put in handler only takePicture method - app works fine (and open camera once and keep it open in onCreate method), but I want to release camera and open it before taking picture to save battery.
I attach my source code and logcat.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Camera mCamera;
private CameraPreview mPreview;
private File pictureFile;
private File mediaStorageDir;
private Context context;
private Handler handler;
public Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("TAG", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("TAG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
Log.d("ftp", "photo taken: " + pictureFile);
mCamera.release();
startFTP();
}
};
private Runnable runnable = new Runnable() {
#Override
public void run() {
try {
mCamera = Camera.open();
} catch (Exception e) {
}
Camera.Parameters params = mCamera.getParameters();
params.setPictureSize(1920, 1080);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
params.set("orientation", "portrait");
params.set("rotation", 90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation", "landscape");
}
mCamera.setParameters(params);
mPreview = new CameraPreview(context, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
try {
this.wait(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.postDelayed(this, 60000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
handler = new Handler();
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
}
);
}
public void startFTP() {
new Thread(new Runnable() {
#Override
public void run() {
Log.d("ftp", "photo uploading started: " + pictureFile);
String sendingPictureName = pictureFile.getName();
String serverAddress = "1111111";
String userId = "111111";
String password = "111111";
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverAddress);
ftp.login(userId, password);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory("/111111");
InputStream input;
input = new FileInputStream(pictureFile);
if (ftp.storeFile(pictureFile.getName(), input)) {
File fileToDelete = new File(mediaStorageDir.getPath() +"/"+ sendingPictureName);
//Log.d("ftp", "sciezka do usuwanego pliku: " + fileToDelete.getAbsolutePath());
fileToDelete.delete();
}
input.close();
Log.d("ftp", "photo uploading ended: " + sendingPictureName);
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private File getOutputMediaFile() {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
public void cancelTimer(View view) {
handler.removeCallbacks(runnable);
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (IOException e) {
Log.d("TAG", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("TAG", "Error starting camera preview: " + e.getMessage());
}
}
}
activity_main.xml - it's layout only for testing and it isn't perfect
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="500px"
android:layout_height="500px"
android:layout_weight="0.1"
android:layout_above="#+id/button_capture" />
<Button
android:id="#+id/button_capture"
android:text="start timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:layout_centerVertical="true" />
<Button
android:id="#+id/timer_button"
android:text="stop timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_below="#+id/button_capture"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:onClick="cancelTimer" />
Logcat:
08-24 09:42:42.828 8935-8935/? E/Zygote﹕ MountEmulatedStorage()
08-24 09:42:42.828 8935-8935/? I/libpersona﹕ KNOX_SDCARD checking this for 10185
08-24 09:42:42.828 8935-8935/? E/Zygote﹕ v2
08-24 09:42:42.828 8935-8935/? I/libpersona﹕ KNOX_SDCARD not a persona
08-24 09:42:42.828 8935-8935/? I/SELinux﹕ Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-A500FU_5.0.2_0023
08-24 09:42:42.838 8935-8935/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
08-24 09:42:42.838 8935-8935/? I/art﹕ Late-enabling -Xcheck:jni
08-24 09:42:42.878 8935-8935/? D/TimaKeyStoreProvider﹕ TimaSignature is unavailable
08-24 09:42:42.878 8935-8935/? D/ActivityThread﹕ Added TimaKeyStore provider
08-24 09:42:42.988 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* installDecor mIsFloating : false
08-24 09:42:42.988 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* installDecor flags : -2139029248
08-24 09:42:43.108 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Render dirty regions requested: true
08-24 09:42:43.118 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
08-24 09:42:43.118 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled return false
08-24 09:42:43.138 8935-8935/com.example.dawid.camerabezpodgladu D/SRIB_DCS﹕ log_dcs ThreadedRenderer::initialize entered!
08-24 09:42:43.138 8935-8951/com.example.dawid.camerabezpodgladu I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: SKARAJGA_AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018+PATCH[ES]_msm8916_32_refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018__release_ENGG (I856e09677e)
OpenGL ES Shader Compiler Version: E031.25.03.02
Build Date: 04/06/15 Mon
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018
Local Patches: 112c106f3772623daa7b4181c6cf23491044ead1 Revert "Disable ASTC on A405"
58a118cb818fdc906095a49a90977c15f9d3b223 Remove ASTC
08-24 09:42:43.138 8935-8951/com.example.dawid.camerabezpodgladu I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-24 09:42:43.158 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Get maximum texture size. GL_MAX_TEXTURE_SIZE is 4096
08-24 09:42:43.158 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Enabling debug mode 0
08-24 09:42:43.258 8935-8935/com.example.dawid.camerabezpodgladu I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#3d659231 time:4110726
08-24 09:42:44.648 8935-8935/com.example.dawid.camerabezpodgladu D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
08-24 09:42:45.678 8935-8935/com.example.dawid.camerabezpodgladu I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
08-24 09:43:45.138 8935-8935/com.example.dawid.camerabezpodgladu W/CameraBase﹕ An error occurred while connecting to camera: 0
08-24 09:43:45.498 8935-8935/com.example.dawid.camerabezpodgladu D/AndroidRuntime﹕ Shutting down VM
08-24 09:43:45.498 8935-8935/com.example.dawid.camerabezpodgladu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.dawid.camerabezpodgladu, PID: 8935
java.lang.RuntimeException: startPreview failed
at android.hardware.Camera.startPreview(Native Method)
at com.example.dawid.camerabezpodgladu.CameraPreview.surfaceCreated(CameraPreview.java:31)
at android.view.SurfaceView.updateWindow(SurfaceView.java:682)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:200)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:921)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1239)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6752)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
at android.view.Choreographer.doCallbacks(Choreographer.java:590)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
08-24 09:43:48.818 8935-8935/com.example.dawid.camerabezpodgladu I/Process﹕ Sending signal. PID: 8935 SIG: 9
Even once method takePicture isn't called. Error is getting from bad realesing camera and reopening it after minute (next handler action).
I will be very thankful for even one tip
Dawid

Finally figured out how to set the phone to take timed pics without any screen display.
There were 2 main issues I struggled with. First, I wanted to take the pics without displaying to screen. Along those lines, I found an example where they used :
mCamera.setPreviewTexture(new SurfaceTexture(10));
and nothing showed on the screen when using this preview method. It appears that some sort of preview is required. Another method was to set the preview to 1 pixel. This method had examples online which appeared to work as well, but I did not try it.
The second and bigger problem had to do with 'onPictureTaken' method. This method processes your picture after the 'takePicture' call. This is where the first answer (above) was tripping me up.
It seemed that no matter what looping method I used, or where in the code the call to 'takePicture' was located, all of the 'onPictureTaken' methods were queued up and called one after another once the parent of the 'takePicture' caller ended.
Although the picture data processed by onPictureTaken were in a proper time sequence, I could see that having several hundred pics stored and waiting to process could cause problems, and a method needed to be found where on pic was processed and stored before the next pic was taken.
Along those lines, I stumbled upon the AlarmManager and coupled that with the BroadcastReceiver and Future classes to solve the problem.
What I've done is set the alarmManger to go off at a set time or time frequency. The BroadcaseReceiver captures this call & in turn calls a method which creates
a thread where a 'Future' object makes the call to take a picture.
'Future' object is nice, because it will wait for the physical camera to take the picture (takePicture) and then process it (onPictureTaken). This all occurs in one thread, then terminates. So no queuing of pics to process and each picture sequence is handled separately.
Code is contained below. Note that some of the default 'Overrides' have been left out to save space. Also, the visible screen was basically a button which captured the click event...very basic.
MainActivity.java:
package myTest.com.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MainActivity extends Activity {
CameraHandler cameraHandler;
public BroadcastReceiver br;
public PendingIntent pi;
public AlarmManager am;
final static private long LOOPTIME = 20000;
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
try{
cameraHandler = new CameraHandler();
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
//Toast.makeText(c, "Taking a pic!", Toast.LENGTH_LONG).show();
TryAThread();
}
};
registerReceiver(br, new IntentFilter("com.timedActivity.activity") );
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.timedActivity.activity"), 0);
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
catch (Exception e){ }
}
private void TryAThread() {
try{
CameraCaller cameraCaller = new CameraCaller(cameraHandler);
Future future = threadpool.submit(cameraCaller);
while (!future.isDone()) {
try {
Thread.sleep(5000);
} catch (Exception ex) { }
}
}
catch (Exception e){ }
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
public void onClickListener(View view){
try{
am.setRepeating(am.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), LOOPTIME, pi);
}
catch (Exception e){ }
}
}
CameraCaller.java:.
package myTest.com.test;
import java.util.concurrent.Callable;
public class CameraCaller implements Callable {
private CameraHandler cameraHandler;
public CameraCaller(CameraHandler ch){
cameraHandler = ch;
}
#Override
public Object call() throws Exception {
cameraHandler.takeAPic();
return true;
}
}
CameraHandler.java:.
package myTest.com.test;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import junit.runner.Version;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){
}
public Boolean takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) {Log.e(Version.id(), e1.getMessage());
}
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
return true;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
try {
Thread.sleep(2000);
}catch (Exception ex){}
}
public static File getOutputMediaFile() {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File mediaStorageDir = new File(file, "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}

Well David, you want 1 tip? I'm working on a similar problem and this may get you a little further down the road...to where I'm currently stuck.
I can take a picture without preview using the following.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraHandler = new CameraHandler();
tryThis();
}
private void tryThis(){
cameraHandler.takeAPic();
}
And the class is:
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){ }
public void takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) { }
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}
catch (FileNotFoundException e) { }
catch (IOException e) { }
}
The problem I'm running into now is that any code I put in following the 'takePicture' is not causing the 'onPictureTaken' to be called.
However, this will at least get you to a spot where you can take a picture without a preview. Maybe you can figure out how to make multiple calls to snap the pictures

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

How to detect every mouse event in system using java

How to detect every mouse event in system using java?
I have tried using Point class to catch mouse motion but that thing was not so convenient.
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
class GlobalKeyListenerExample implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
public GlobalKeyListenerExample()
{
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);
}
GlobalScreen.getInstance().addNativeKeyListener(this);
}
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 and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(new GlobalKeyListenerExample());
}
}

Eclipse Project dependencies dont work when exported

I am currently facing following big problem:
I have a Framework-Project (maven), where a PropertyReader is included (reads "config.properties" in the same package and returns its values):
This is the Framework-Project:
public class PropertyReaderFramework {
private static Properties props;
private static void init(){
String filename = "com/ks/framework/properties/config.properties";
InputStream input = PropertyReaderFramework.class.getClassLoader()
.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
props = null;
} else {
props = new Properties();
}
try {
props.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key){
if(props == null) init();
return props.getProperty(key);
}
public static Properties getProperties(){
if(props == null) init();
return props;
}
}
And my main-project, where I need the information of the properties-file just has one class (for demonstation):
package testmsg;
import com.ks.framework.properties.PropertyReaderFramework;
public class main {
public static void main(String[] args) throws InterruptedException {
try {
String basepath = PropertyReaderFramework.getProperty("remoteFileAccess.script.location");
System.out.println(basepath);
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.sleep(5000);
}
}
}
The funny thing is, that if I execute the main() class in eclipse, it reads the value from the properties correctly.
But when I export it as a runnable JAR, it throws me following error:
Can anyone help me to solve this problem? I cannot figure out why it behaves like that...

How to set a web page while clicking on a button ? with JavaFX

i'm trying to get an URL from TextField exapmle: http://www.google.com and i have a WebViewthat it will be visible by clicking on the "Enter key" but the problem is when i run the application it didn't show anything note that i'm using FXML File.This is the code i've traied:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
//c.1
if(text1.getText().equals("1")){
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
//do work
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load("http://www.google.com");
//close the window chooser
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
So please can any body explain for me where is the problem for this code and i'll be so thankful :)
Here is a simple example application that goes to the web page you typed in when you press enter in the text field:
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
final TextField text1 = new TextField();
WebView web = new WebView();
final WebEngine webEngine= web.getEngine();
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
if (ke.getCode().toString().equalsIgnoreCase("ENTER")) {
String urlString = text1.getText().trim();
webEngine.load(urlString);
}
}
});
pane.getChildren().addAll(web,text1);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch("application.Main");
}
}
You can try typing in https://www.google.com and it should take you there
If you exclude the http or https it should not work
Depending on your jre you may need to remove the #Override
I hope this helps
I am not really sure if you want 'if(text1.getText().equals("1")){' the if statement will only be true if someone types in the character "1" but how you set the web engine is by getting the text from the text field (text1) and getting the web engine to load it and it is good practice to put a .trim() at the end incase the user accidentally types in a space at the beginning of the end.
So your code should look something like this:
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
And you complet code should look something like this:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
I hope this helps. If you have any questions just ask.

capturing the image using android camera [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling camera from an activity, capturing an image and uploading to a server
i am very new to android, i am trying to capture the image after that i placed that image into image view,its working on emulator but in device it crashes it shows the message force close even it cannot open the camera activity.the following is my code.
please help me how to solve this problem.thank you.
package com.gss.android;
package com.gss.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Pictures extends Activity{
Button btnsave,btnnewpic;
protected ImageView image;
protected String _path;
File sdImageMainDirectory;
private static final int IMAGE_CAPTURE = 0;
protected boolean _taken = true;
private Uri imageUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAMERA_PIC_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictures);
btnsave=(Button)findViewById(R.id.btnsave);
btnnewpic=(Button)findViewById(R.id.btnnewpic);
btnnewpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCameraActivity2();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK){
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
Log.e("file path", "stiring file") ;
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
}
} else if ( requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDRO_CAMERA","Picture taken!!!");
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(imageUri);
}
}
}
protected void startCameraActivity2()
{
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(Pictures.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(Pictures.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
Log.e("file dir",imageDir.toString());
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think this is a problem related to the emulator and not the physical device.
I used this code and I got a bitmap:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
imageView = (ImageView)findViewById(R.id.image);
destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
//Bitmap userImage = (Bitmap)data.getExtras().get("data");
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10; //Downsample 10x
Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
imageView.setImageBitmap(userImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Add extra to save full-image somewhere
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
Toast.makeText(JMABarcodeScannerActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(intent, REQUEST_IMAGE);
}
};
}
Main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"
/>
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
/>
</LinearLayout>