Camera Trigger Source Code - Windows Mobile Development and Hacking General

A long time ago I wrote some code to work as a timer app for the camera on the Himalaya. I've had a couple of emails about this recently so thought I would post the important parts of code for firing off the camera here. Before it's lost forever as I have a Magician these days.
First I start the camera app:-
Code:
void CCameraTimerDlg::RunCameraApp()
{
// setup parameters for ShellExecuteEx
SHELLEXECUTEINFO sei;
memset(&sei,0,sizeof(SHELLEXECUTEINFO));
sei.cbSize=sizeof(SHELLEXECUTEINFO);
sei.hwnd=::GetDesktopWindow();
sei.lpFile=TEXT("\\Windows\\Camera.exe");
sei.nShow=SW_SHOW;
// start the camera app running (or if it's already running switch to it)
ShellExecuteEx(&sei);
}
Then get a handle to it's command window and take the photo:-
Code:
void CCameraTimerDlg::TakePicture()
{
// Find main Camera App window
HWND hCameraApp=::FindWindow(TEXT("WCE_IA_Camera_Main"),NULL);
// if we found it okay....
if (hCameraApp)
{
// find the Camera App's first child window (it's UI)
HWND hCameraSkin=::GetWindow(hCameraApp,GW_CHILD);
// if we found it okay ...
if (hCameraSkin)
{
// press the "take photo" button
::SendMessage(hCameraSkin,WM_COMMAND,0xBC4,0x00);
// wait while photo is taken
::Sleep(500);
// press "save photo" button
::SendMessage(hCameraSkin,WM_COMMAND,0xBD4,0x00);
}
}
}
and then quit the camera app
Code:
void CCameraTimerDlg::ExitCameraApp()
{
// find the Camera App's main window
HWND hCameraApp=::FindWindow(TEXT("WCE_IA_Camera_Main"),NULL);
// if we found it okay, ask it to close
if (hCameraApp)
::SendMessage(hCameraApp,WM_CLOSE,0,0);
}

Related

Motion trigger for WM device

I will be using a PIR sensor as a motion detection and the relay connected to 2 wires hard wired to either a button or key on a WM PDA or smartphone.
I have this working on a smartphone on the cursor up (Joypad).
What c# code do I need to:
Read the first keypress ( take a series of images)
Ignore all keypress until (take a series of images has finished).
Start process again
or
Read the first keypress ( take a series of images) until
Keypress has finished (ie the switch is open)
As a test I used two edit boxes. When the switch is closed the cursor moves from each textbox changing the text in the box.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
private void textBox2_GotFocus(object sender, EventArgs e)
{
textBox2.Text = ("moved");
}
private void textBox1_GotFocus(object sender, EventArgs e)
{
textBox2.Text = ("moved again");
}
I can then action the camera call when textBox2.text is changed.
Any info appreciated.
SteveW

Help writing something with setOnItemClickListener

In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...

[Q] Repeat Button Action

Hello. New here and I hope this post is okay. The "Is this a question?" checkbox says it not the QA forum but it is?
Working on an app that all it's supposed to do is repeat taking a picture every 5 seconds after pressing a button. Now, I've looked at handler, timer, etc but I can't figure out the right way to do it. This is the code currently, and the onCameraClick of course runs when the button on the screen is pressed. I want that button to activate some kind of repeater so the picture gets taken every 5000ms.
Code:
public class CameraImage extends Activity {
public static int cameraID = 0;
public static ImageView image;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraimage);
image = (ImageView) findViewById(R.id.imgView);
}
public void onCameraClick(View v)
{
cameraID = 1;
Intent i = new Intent(CameraImage.this, CameraView.class);
startActivityForResult(i, 9999);
}
}
Now, this is something I'd definitely like to use but I'm not sure how to implement this correctly into the code above. Been trying trial and error for past few hours and nothing. Tried out a timer example someone put on another website, 10792454/image-capture-in-android-automatically but not much there.
At the same time however though, I'm not sure if the code should go in the other class with all the functions to run the camera. Any suggestions/tip or help I'd greatly appreciate it.
Try a loop. I'm not sure if you have tried this or if it will work with launching an activity, but it sounds like that is what you want to do. I don't know how you determine when to stop taking pictures but you can use a "for loop" or a "while loop".
example "for loop":
Code:
for (int i; i > someNumber; i++){
//Your code here
}
someNumber would be perhaps the number of pictures you want to take and you can use i to number each picture.
example "while loop":
Code:
Boolean buttonClick = false;
onCreate(){
OnButtonClick(){
OnClick(){
if(buttonClick == true){
buttonClick = false;
}else{
buttonClick = true;
}
onCameraStart(buttonClick);
}
public void onCameraStart(boolean runCamera){
while (runCamera == true){
//Your code here
}
}
This example I showed you how you would be able to start the camera on the first click and stop it when clicked again. The OnButtonClick would be the OnClickListener for your button.
Both these examples may need a little refinement but this should point you in the right direction. Hope this helps. You can put these in threads and pause the thread at the end of the loop for 5 secs so it will wait (I think).
It's simple use a timer and invoke it on first click
Sent from my GT-S5302 using Tapatalk 2

[Q] Issues with adding objects to a photo taken by the user

I've been trying to learn to program for Android lately by simply coming up with ideas and implementing them. It started out easy enough with pulling information from an online RSS feed and showing this in a nice environment. But the current idea has me stumped.
I'd like the following to happen:
Take a picture using intent
Entire picture is shown in a new activity
Zoom in on a certain spot
Add predefined items to the picture
Press next which connects the items from left to right
Add some more items
Press next to connect the new items
Zoom out
Save the image
First taking a picture, this wasn't too hard using the camera intent:
Code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
I can then extract the absolute path from fileUri with the following line:
Code:
String path = new File(fileUri.getPath()).getAbsolutePath();
This path can be put in a bundle which can be put in an intent which is then used to start the activity that should show the image.
Code:
public class TestActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = TestActivity.class.getSimpleName();
private String path = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SurfaceView view = new SurfaceView(this);
setContentView(view);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
path = bundle.getString("path");
view.getHolder().addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.d(TAG,"Can't draw because canvas is null");
}
else {
Bitmap bitmap = BitmapFactory.decodeFile(path);
Paint paint = new Paint();
if(bitmap == null) {
Log.d(TAG,"Can't draw because bitmap is null");
}
else {
canvas.drawBitmap(bitmap,0,0,paint);
}
holder.unlockCanvasAndPost(canvas);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int frmt, int w, int h) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
The first issue here is that it of course doesn't show the entire photo. Not that surprising considering it's larger than the view. Ideally I'd like to zoom out to show the entire photograph. Once I've zoomed one way I'd assume that zooming in on the part that you want should also be possible.
Next is adding the objects. My idea was simply catching any touch events and adding a new object once the finger is released. This way I'd end up with a list of items with each having a draw function which can be called through the surfaceview when it is redrawn.
Connecting these items could simply be done by creating a line object and going through the list of all items and using their locations for the begin and endpoints of the lines
One of the big issues here is that the x and y locations would be relative to the screen, not to the photo. Which would mean that when you zoom back out the entire background would change but the actual items would remain at the same spot and in the same size.
I've been searching and searching for any tutorial or other question about the same issue, but either I've had no luck or I've been using the wrong keywords. And for all I know everything I have up till now could be wrong.
If anyone could give some pointers, or maybe knows a guide or tutorial somewhere or some better keywords I could use for searching I'd really appreciate it.
Xylon- said:
One of the big issues here is that the x and y locations would be relative to the screen, not to the photo. Which would mean that when you zoom back out the entire background would change but the actual items would remain at the same spot and in the same size.
Click to expand...
Click to collapse
would you just not need to either control or track the sample/scale if the image so that you know the 1st pixel displayed (top left) and the scale factor, then the eventX/Y can be processed to be relative to what you want ?

[Tutorial] Programming for Sony Products [Xperia Camera.AddON][SourceCode]

Programming for Xperia Smartphones (Camera Add-On)​
Camera Add-on feature on Xperia Camera App is way to gather all custom camera apps, that the may have New/Different way to Capture pictures. Maybe some Graphical Effects or as you will see in this tutorial another way to capture.
This is How Sony Mobile Devs explain the CameraW Add-On
All camera apps in one menu
The Camera Add-on API enables you to both add a shortcut to your imaging app from the camera apps mode selector, and you can add a shortcut to the smart social camera apps mode selector in your imaging app UI. This way the user can get a seamless camera experience, and make shifting in-between different camera apps really easy. read more...
Click to expand...
Click to collapse
Examples of Camera Add on App
- Live on YouTube – by Xperia™
- AR Effect
- Background Defocus
- Horror
- CameraW
### Let Start ###​
What you need is ability to create Hello World! project
In this Tutorial you Learn How to Create your Camera App
&​ Adding Xperia Camera Add-On Support
Click to expand...
Click to collapse
1. Install Sony Add-On SDK
- Open Android SDK Manager
- Tools > Manager Add-on Sites > User Defined Sites > New
- Now Enter this URL
HTML:
http://dl-developer.sonymobile.com/sdk_manager/Sony-Add-on-SDK.xml
- Close the Add-on Tools
- Relaunch SDK Manager & Go to Android API-19 section & Download
HTML:
Sony Add-on SDK-3.0
***
Ready to Programming for Xperia
^-^-^​ 2... (Click On Tutorial Link)
​ Tutorial to Start Programming for Xperia Camera Add-On
:Sample Codes:
#CaptureProximity
Don't forget to Hit Thanks​
Tutorial to Start Programming for Xperia Camera Add-On
2. Starting...
- Create New Android Project (Alt + Shift + N)
* Minimum Requirement: API 16
* Target: API 19/20
* Compile with: Sony Add-on SDK 3.0 (API-19)
Note:You can Add Xperia Camera Add-On support to your current custom camera Application by Adding few elements to your app.
- from Bottom to Top
This Sample as first sample is just modified Basic_Sample from SonyMobile
Modified to Capture & Save Image By Hovering Proximity Sensor
Click to expand...
Click to collapse
​* Open Manifest & Add require Permissions for using Add-On API, Camera Hardware & Storage.
The Storage permission is for create file in SD-Card for capture pics and Camera to get permission from system to allow us to use Camera hardware.
Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="com.sonymobile.permission.CAMERA_ADDON"/>
- Declare required library inside Application in manifest
Code:
<!-- If you want to create a camera app for just Xperia device you should set[B] required="true"[/B]. False means your can be install on other devices-->
<uses-library android:name="com.sonymobile.camera.addon.api" android:required="false"/>
- Then you will have your Activities declaration. You should add specific Intent-Filter & Meta-Data for the Activities that you want show on Camera Add-On menu. In this sample I set it for main activity.
Code:
<activity
android:name=".BasicCameraApp"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:windowSoftInputMode="stateAlwaysHidden"
android:launchMode="singleTask" >
<!-- The widowSoftInputMode is preferred to use But
launchMode="singleTask" must be set because there is another apps in Add-On menu that can launch or
switch between different modes -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.sonymobile.camera.addon.action.REGISTER_MODE" />
</intent-filter>
<meta-data android:name="com.sonymobile.camera.addon.MODE_ATTRIBUTES"
android:resource="@xml/sample_mode" />
<!-- This XML file save all required attributes for Info show in add-on menu and etc-->
</activity>
* Under res/ create xml folder & then .xml file to generate required meta-data
HTML:
res/xml/sample_mode.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<modes xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Do Not hard-code your won't register as add-on -->
<mode
<!-- [B]Remember [/B]the name="" because you need this to use it in classes cause this name will register
If you set incorrect your mode won't be available in modes menu -->
name="cameraw"
descriptionLabel="@string/app_name"
selectorIcon="@drawable/mode_icon"
shortcutIcon="@drawable/mode_shortcut_icon"
selectorLabel="@string/app_name"
shortcutLabel="@string/app_name" >
<uses-feature android:name="android.hardware.camera" />
</mode>
</modes>
* In layout folder you should add element for Preview of Camera. You can use TextureView, SurfaceView & FrameLayout. In this basic sample there is SurfaceView.
* In drawable you should add file for icon & shortcut of your add-on that must follow the guidelines. For better understand I upload the Xperia Camera drawable resources + what you can check in Sample Code drawable.
* Now Coding...
Code:
import com.sonymobile.camera.addon.capturingmode.CapturingModeSelector;
First you should define as specific parameter of Camera Add-On API
Code:
/**This class opens and closes the capturing mode selector. The mode selector provides access to all registered camera modes for camera add-ons available to the user. All methods must be called from the UI thread. **/
CapturingModeSelector mCapturingModeSelector;
- Then you need to define two listener for Selecting process & while closing the modes menu;
Code:
public static final String MODE_NAME = "cameraw";
Code:
private class MyOnModeSelectListener implements CapturingModeSelector.OnModeSelectListener {
Override
public void onModeSelect(String modeName) {
if (mCapturingModeSelector != null) {
mCapturingModeSelector.close();
mModeSelectorButton.setVisibility(View.VISIBLE);
}
}
}
Code:
private class MyOnModeFinishListener implements CapturingModeSelector.OnModeFinishListener {
Override
public void onModeFinish() {
if (mCapturingModeSelector != null) {
mCapturingModeSelector.close();
}
finish();
}
}
- The Handle the Click & Touch on Mode Button
Code:
private class ModeSelectorButtonTouchListener implements View.OnTouchListener {
Override
public boolean onTouch(View v, MotionEvent event) {
mModeSelectorButton.onTouchEvent(event);
if (mModeSelectorButton.isPressed()) {
mModeSelectorButton.setColorFilter(PRESSED_COLOR_FILTER);
} else {
mModeSelectorButton.clearColorFilter();
}
return true;
}
}
Code:
private class ModeSelectorButtonClickListener implements View.OnClickListener {
Override
public void onClick(View v) {
if (mCapturingModeSelector != null) {
[B]// This is name attributes in .xml file as meta-data[/B]
mCapturingModeSelector.open(MODE_NAME);
mModeSelectorButton.setVisibility(View.INVISIBLE);
mModeSelectorButton.clearColorFilter();
}
}
}
- Then at Override onCreate you should define them;
Code:
mModeSelectorButton.setOnClickListener(new ModeSelectorButtonClickListener());
mModeSelectorButton.setOnTouchListener(new ModeSelectorButtonTouchListener());
- & on @override onResume these. onResume for these to handle their action when user back to your app that she didn't close it completely so she need modes selector to switch modes;
Code:
mCapturingModeSelector.setOnModeSelectListener(new MyOnModeSelectListener());
mCapturingModeSelector.setOnModeFinishListener(new MyOnModeFinishListener());
NOTE: These are mandatory in your Activity that want to support add-on.
If you have already Camera App you should add what previously said up to here and you done!
It means these are common elements that you should add for Camera Add-On support.
^^^
^^^
*** Sample Codes ***
​* How to Capture By Proximity Sensor?
I.
Code:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
II. implements you activity from SensorEventListener
Code:
public class BasicCameraApp extends Activity implements SensorEventListener{}
III. Override onCreate(Bundle Saved){} you must declare instance of Sensor & SensorManager
Code:
//define [COLOR=Blue][B]sensorManager [/B][/COLOR]& declare which sensor do you want to use
//that here is [COLOR=Blue][B]Proximity_SENSOR[/B][/COLOR]
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
Then you need to register the sensor to get data from it at Override onResume(){} cause this must be available for user when back to your app.
Code:
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
Now you have interaction with proximity sensor so we need to capture function and integrate it with sensorEvent.
Note: Always Unregister Sensors when user leave your app. It means you should release the camera, and all other sensor you are using in your app
Code:
Override
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(this);
mCameraWrapper.mCamera.release();
}
IV. Then define PictureCallback to handle received data from Camera Lens and write them to File.
Code:
private PictureCallback mPicture = new PictureCallback() {
Override
public void onPictureTaken(byte[] data, Camera camera) {
//Here you will have array of data from camera and save these data to file as picture
// there is almost always separate function to handle name files and extension
// and here just write byte[] data to that file
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
// NOTE: Handle the image rotation after saving the file.
try {
// [B]pictureFile[/B] that created in [B]getOutputMediaFile()[/B] function now set to FileOutputStream
FileOutputStream fos = new FileOutputStream(pictureFile);
//here bye[] data write in created file.
fos.write(data);
fos.close();
Toast.makeText(getApplicationContext(), "Captured", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
}
catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
finally {
//start camera preview after file created and data wrote in it.
mCameraWrapper.mCamera.startPreview();
}
}
};
Code:
public static final int MEDIA_TYPE_IMAGE = 1;
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AddOn_GeeksEmpire");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("CameraW", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
//this is empty jpg image file with timestamp to prevent overwrite
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "AddON_"+ timeStamp + ".jpg");
}
else {
return null;
}
return mediaFile;
}
>> After this we just need to call takePicture() function to take a pic...
V. When you implements the activity from SensorEventListener it will ask you to add unimplemented methods, that will be these two function at least.
Code:
Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
Override
public void onSensorChanged(SensorEvent event) {
//Proximity Sensor detect near interaction ~5cm
//in this case of sensor type system have one
float p = event.values[0];
System.out.println("Proximity >> " + p);
if(p == 0){
//here i call takePicture function when value of Sensor (destination) be 0
// like tap on sensor or hover nearly
mCameraWrapper.mCamera.takePicture(null, null, mPicture);
}
}
There should be also a Class that handle the surfaceView for preview of Camera Because It is easy to understand and not any special point in this simple example I just wrote detail inside the CameraWraper.class
Just few code...
- You define Camera parameter & then use Open(int id) function to launch camera & after this use startPreview() function to see live view through camera lens.
So First you need to add Preview (SurfaceView) & then use Camera.
In this sample...
Code:
SurfaceView surfaceView = (SurfaceView)findViewById(R.id.surface);
CameraWrapper mCameraWrapper = new CameraWrapper(); //class that handle the preview
surfaceView.getHolder().addCallback(mCameraWrapper);
Code:
Camera mCamera;
try{
mCamera.open(); /*Or you can use open(int id) the id can define the front & back camera. usually if you don't set id it will launch back camera (int id = 0)*/
} catch (RuntimeException e) {
// here is good point to handle errors if there is problem with Camera maybe from other app or System.
} finally{
mCamera.startPreview();
}
Note: You can use these inside camera preview class or directly in activity class.
Note: When there is change in surfaceView, change the orientation for instance, first you should stop the live view, apply new configuration and then startPreview().
Code:
Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
//
}
}
End of Proximity Capture |
OOOOOOO
The explanations of codes are available inside each classes.
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
Don't forget to Hit Thanks​
Sorry, I just forgot to write about Camera Preview Handler, So updated the Tutorial Post.
Good Luck

Categories

Resources