Switch Custom Camera Front and Back in Android - java

I Want To Add A Switch Camera Button To My Code.
Here is The Code.
I am not getting how do i do it.
Please Suggest Some Methods.
Thank you in Advance.
CameraDemo.java
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick,switchCam;
int which=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switchCam=(Button)findViewById(R.id.switchcam);
preview = new Preview(this);
((RelativeLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm");
// Setting Dialog Message
alertDialog.setMessage("Are You Done ?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.doneimg);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Student");
// Setting Dialog Message
alertDialog.setMessage("Are you a Student?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.student);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Intent i = new Intent(getApplicationContext(),
ScanId.class);
startActivity(i);
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
long time = 0;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
time = System.currentTimeMillis();
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",time));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
NExxt Java File >> Preview.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
int which=0;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/layout">
<RelativeLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/switchcam"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
<Button android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/buttonClick"
android:text=""
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/circlebutton"
/>
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/gallery"
android:background="#drawable/grid"
android:layout_marginBottom="50dp"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

Just reopen camera with open(int cameraId) method.
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);

Related

Image not save in the device when click the button

Currently, I am using the Picasso library to download images and save it in the device when I press the button. the problem is when I press the button the image not download and just shown the message "Image Downloaded" , so how can i fix it? Here is my code
PicassoDisplayImageAdapter.java
/*
* This class for display the image when clicking on it
* It gets the data from the class have the images "Images in ArrayList"
* Also It is for download images
*/
public class PicassoDisplayImageAdapter extends AppCompatActivity {
public static final int PERMISSION_WRITE = 0;
String fileUri;
Button download_image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
/* Display the data in the ImageView with Picasso "ImageView that insert in he activity" */
final ImageView imageView = findViewById(R.id.image_display);
final Intent intent = getIntent();
if (intent.hasExtra("imageUrl")){
String url = intent.getStringExtra("imageUrl");
Picasso.with(this)
.load(url)
.fit() // to resize the image to imageView
.placeholder(R.drawable.progress_animation)
.error(R.drawable.error)
.into(imageView);
}
/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
});
}
/* method to save image*/
private void SaveImage(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File mydir = new File(Environment.getExternalStorageDirectory() + "/11zon");
if (!mydir.exists()) {
mydir.mkdirs();
}
fileUri = mydir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
FileOutputStream outputStream = new FileOutputStream(fileUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Image Downloaded", Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
/* runtime storage permission */
public boolean checkPermission() {
int READ_EXTERNAL_PERMISSION = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if((READ_EXTERNAL_PERMISSION != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_WRITE);
return false;
}
return true;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==PERMISSION_WRITE && grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//do somethings
}
}
}
ImagesRamadanActivity.java That has the data
/*
* This Activity for display the ramadan images
* This class has the data of images
*/
public class ImagesRamadanActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ramadan_images);
/* ArrayList for RamadanImages */
final String[] RamadanImages = {
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
};
/* make new object and find the view "GridView" */
GridView gridView2 = findViewById(R.id.gridview_image_ramadan);
// display all the images from Array on it
gridView2.setAdapter(new PicassoImagesAdapter(ImagesRamadanActivity.this, RamadanImages));
/* display the image when click on it */
// we made a class for this method "the class called PicassoDisplayImageAdapter"
gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the image
String image = RamadanImages[position];
Intent intent = new Intent(ImagesRamadanActivity.this, PicassoDisplayImageAdapter.class);
intent.putExtra("imageUrl", image);
ImagesRamadanActivity.this.startActivity(intent);
}
});
activity_image_display.xml activity to display the photo and has the button to download the image
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageView>
<Button
android:id="#+id/button_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="download the image"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp" />
</RelativeLayout>
Inside,
onCreate(){
setContentView(..);
// requestPermission. ask for permission when app starts.
}
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
// kind of this, add this block to your existing code.
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
// make sure Manifest has all the permission defined

Android Studio Display Image in Alert Dialog

I have an image store in the firebase realtime db as a url. I am trying to download the image and display the image in an alert dialog message. When excuting the code the alert dialog appears but no image is displayed.
ImageDownloader Class:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownload extends AsyncTask<String, Void, Bitmap>
{
private final WeakReference<ImageView> imageViewWeakReference;
public ImageDownload(ImageView imageView)
{
imageViewWeakReference = new WeakReference<>(imageView);
}
#Override
protected Bitmap doInBackground(String... string)
{
return downloadBitmap(string[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap)
{
if(isCancelled())
{
bitmap = null ;
}
ImageView imageView = imageViewWeakReference.get();
if (imageView != null)
{
if (bitmap != null)
{
imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap downloadBitmap(String url)
{
HttpURLConnection connection = null;
try
{
URL url1 = new URL(url);
connection = (HttpURLConnection) url1.openConnection();
int StatusCode = connection.getResponseCode();
if(StatusCode != connection.HTTP_OK)
{
return null;
}
InputStream inputStream = connection.getInputStream();
if(inputStream != null)
{
return BitmapFactory.decodeStream(inputStream);
}
}
catch (Exception e)
{
connection.disconnect();
}
finally
{
if(connection != null)
{
connection.disconnect();
}
}
return null;
}
}
I created a layout xml file for the alert dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/dialog_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
btVoucher1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
String qrcode = dataSnapshot.child("Voucher").child("1").getValue().toString();
Toast.makeText(getActivity(), qrcode, Toast.LENGTH_LONG).show();
AlertDialog.Builder alertVoucher1 = new AlertDialog.Builder(getContext());
alertVoucher1.setNeutralButton("Close",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
new ImageDownload(qrCodeVoucher).execute(qrcode);
AlertDialog voucher = alertVoucher1.create();
voucher.show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
});
Can anyone provide any help? Thank you.
Here I could see you are parallelly loading the image on async task , which may take some time to download the image and before that you have called the alert dialog. So before the image comes up alert is shown.
Solution : You can call of alert dialog shown from the postExecute() of asyncTask , that will work perfectly.
you have created a Layout for that but you didn't use it anywhere I think you are new here whatever you are doing can be done by using a Dialog and Not by using an AlertDialog Here I am giving you an example :
// Create a custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.your_dialg_layout);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image or button
ImageView image = dialog.findViewById(R.id.your_imageview_id);
// image.setImageResource(R.drawable.image0);
now, Instead of creating an AsyncTask I suggest you to Use Glide or Picasso (libraries to load URLs in ImageView)
and You also have to create a dismiss button in your Dialogs Layout
dialog.show();
Button declineButton = dialog.findViewById(R.id.your_dialog_button);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
happy coding :)

Android to Arduino via Bluetooth. App won't send string

I found some code in the Internet and changed it. I try to send a short string via Bluetooth. I use the HC-05 Bluetooth module.
I can connect my android device with the module but I can't send a string to my Arduino.
I have:
1 EditText to enter my string.
2 Buttons:
-1 to send
-2 to connect
Could you look over my code? Thank you:)
Android Code...
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
String command;//string variable that will store value to be transmitted to the bluetooth module
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button BtSend = findViewById(R.id.BtSend);
Button BtVerbinden = findViewById(R.id.BtVerbinden);
final EditText EtEingabe = findViewById(R.id.EtEingabe);
BtSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
command = EtEingabe.getText().toString();
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
//Button that connects the device to the bluetooth module when pressed
BtVerbinden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BTinit()) {
BTconnect();
}
}
});
}
public boolean BTinit() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
boolean connected = true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream == null) {
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
}
}
return connected;
}
#Override
protected void onStart() {
super.onStart();
}
}
Android XML...
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.swini.gimbalarduino.MainActivity">
<Button
android:id="#+id/BtSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="184dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/EtEingabe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="220dp"
android:ems="10"
android:hint="Hoi"
android:inputType="textPersonName"
android:text="Text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/BtVerbinden"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Connect"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Try to use this code but this code run in Fragment so carefully change the Code according to your activity.
package com.example.rishabhrawat.tablayoutapp;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
/**
* Created by Rishabh Rawat on 6/18/2017.
*/
public class OfflineVideo extends android.support.v4.app.Fragment {
Button f,r,l,b,s,dis;
ListView listView;
ImageView mic;
BluetoothAdapter adapter;
private Set<BluetoothDevice> paireddevices;
private String address;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private ProgressDialog progress;
private final int REQ_CODE_SPEECH_INPUT = 100;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.offlinevideo,container,false);
f=(Button)view.findViewById(R.id.forward);
r=(Button)view.findViewById(R.id.right);
l=(Button)view.findViewById(R.id.left);
b=(Button)view.findViewById(R.id.backward);
s=(Button)view.findViewById(R.id.stop);
dis=(Button)view.findViewById(R.id.discover);
mic=(ImageView)view.findViewById(R.id.mic);
listView=(ListView)view.findViewById(R.id.listview);
f.setEnabled(false);
r.setEnabled(false);
l.setEnabled(false);
b.setEnabled(false);
s.setEnabled(false);
mic.setEnabled(false);
adapter=BluetoothAdapter.getDefaultAdapter();
dis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowPairedDevices();
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward();
}
});
r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
right();
}
});
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
left();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backward();
}
});
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VoiceInput();
}
});
return view;
}
public void ShowPairedDevices()
{
paireddevices=adapter.getBondedDevices();
ArrayList list = new ArrayList();
if (paireddevices.size()>0)
{
for(BluetoothDevice bt : paireddevices)
{
list.add(bt.getName() + "\n" + bt.getAddress());
}
}
else
{
Toast.makeText(getContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter=new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(myclicklistner);
}
private AdapterView.OnItemClickListener myclicklistner= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
new connectbt().execute();
}
};
private class connectbt extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(getActivity(), "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
adapter = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = adapter.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(getActivity().getApplicationContext(),"Connection Failed Please Try again later",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Successfully Connected ", Toast.LENGTH_SHORT).show();
f.setEnabled(true);
r.setEnabled(true);
l.setEnabled(true);
b.setEnabled(true);
s.setEnabled(true);
mic.setEnabled(true);
isBtConnected = true;
}
progress.dismiss();
}
}
public void toast(String message)
{
Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void forward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void left()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("L".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void right()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("R".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void backward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("B".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void stop()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("S".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
public void VoiceInput()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speak Command for Robot");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQ_CODE_SPEECH_INPUT)
{
if(resultCode==RESULT_OK)
{
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).equals("forward"))
{
forward();
}
else if(result.get(0).equals("backward"))
{
backward();
}
else if(result.get(0).equals("stop"))
{
stop();
}
else if(result.get(0).equals("left"))
{
left();
}
else if(result.get(0).equals("right"))
{
right();
}
else
{
Toast.makeText(getActivity(), result.get(0), Toast.LENGTH_SHORT).show();
}
}
}
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/stop"
android:layout_alignStart="#+id/stop"
android:layout_marginBottom="27dp" />
<Button
android:id="#+id/backward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/forward"
android:layout_centerVertical="true"
android:text="Backward"
/>
<Button
android:id="#+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="14dp"
android:text="Left"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/backward"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#00bfff"
android:textColor="#fff"
android:layout_alignTop="#+id/left"
android:layout_marginStart="17dp"
android:text="Right" />
<Button
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:background="#d22d2d"
android:textColor="#fff"
android:layout_alignBaseline="#+id/right"
android:layout_alignBottom="#+id/right"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/backward"
android:divider="#52f202"
android:dividerHeight="1dp"
android:id="#+id/listview"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<Button
android:id="#+id/discover"
android:background="#80ff00"
android:textSize="25dp"
android:textColor="#000099"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-smallcaps"
android:text="Discovery"
android:textAppearance="#style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" />
<ImageView
android:id="#+id/mic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/discover"
app:srcCompat="#drawable/microphone" />
</RelativeLayout>
Arduino Code
char myserial;
void setup()
{
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(8,OUTPUT);
Serial.begin(9600);
}
void loop()
{
myserial=Serial.read();
switch(myserial)
{
case 'S':
digitalWrite(11,LOW);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,LOW);
break;
case 'B':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
case 'F':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'L':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'R':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
}
}
btSocket.getOutputStream().write(sendText.getText().toString().getBytes());
.

Take picture and Save picture after button is pressed

Need help on creating a method that will capture a picture, and a method that will save it if a button is pressed.
Currently, the camera is being displayed inside a TextureView as soon as the app starts and I am struggling to find a way to capture and save pictures.
It doesn't really matter if it captures from screen or from the actual phone camera.
Github: https://github.com/Chalikov/group26/tree/experimental
Thank you.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAMERA_PERMISSION = 200;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "AndroidCameraApi";
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest.Builder captureRequestBuilder;
private Button takePictureButton;
private Button retryButton;
private Button acceptButton;
private TextureView textureView;
private String cameraId;
private Size imageDimension;
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//open your camera here
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Transform you image captured size according to the surface width and height
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
private ImageReader imageReader;
private Uri file;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
#Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private HandlerThread mBackgroundThread;
private View view;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
textureView = (TextureView) findViewById(R.id.texture);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
takePictureButton = (Button) findViewById(R.id.btn_takepicture);
assert takePictureButton != null;
takePictureButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
takePicture();
takePictureButton.setVisibility(View.INVISIBLE);
retryButton = (Button) findViewById(R.id.btn_retry);
acceptButton = (Button) findViewById(R.id.btn_analyze);
retryButton.setVisibility(View.VISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
retryButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
retryButton.setVisibility(View.VISIBLE); //SHOW the button
acceptButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
acceptButton.setVisibility(View.VISIBLE); //SHOW the button
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void takePicture() {
}
protected void savePicture() {
}
// private static File getOutputMediaFile(){
// File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES), "CameraDemo");
//
// if (!mediaStorageDir.exists()){
// if (!mediaStorageDir.mkdirs()){
// return null;
// }
// }
//
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// return new File(mediaStorageDir.getPath() + File.separator +
// "IMG_"+ timeStamp + ".jpg");
// }
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
texture.setDefaultBufferSize(height, width);
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onResume() {
takePictureButton.setVisibility(View.VISIBLE);
super.onResume();
Log.e(TAG, "onResume");
startBackgroundThread();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
#Override
protected void onPause() {
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
Log.e(TAG, "onPause");
stopBackgroundThread();
super.onPause();
closeCamera();
}
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.project26.MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextureView
android:id="#+id/texture"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/btn_takepicture"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="80dp"
android:background="#drawable/camera_button"
android:visibility="visible"/>
<Button
android:id="#+id/btn_retry"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="left|bottom"
android:layout_marginBottom="80dp"
android:layout_marginLeft="60dp"
android:background="#drawable/retry"
android:visibility="invisible" />
<Button
android:id="#+id/btn_analyze"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="right|bottom"
android:layout_marginBottom="80dp"
android:layout_marginRight="60dp"
android:background="#drawable/analyze"
android:visibility="invisible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical|bottom"
android:background="#4D000000"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Gallery"
android:textColor="#fff"
android:textSize="12sp"/>
<Button
android:id="#+id/camera_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Camera"
android:textColor="#fff"
android:textSize="12sp"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
//Modify Id and names according to your project.
//below onclick listener takes pic
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
//override onPictureTaken method, write the below code that saves it to a file.
File pictureFile = PATHOFYOURLOCATION;
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
Log.d(TAG, "written");
Toast.makeText(getApplicationContext(), "image saved in "+pictureFile, Toast.LENGTH_SHORT).show();
fos.close();

How to toggle flashlight mode?

I want to add a button (which I have included in my activity_main) to my app that will launch a strobe effect when pressed and will stop when pressed again. I do not care about the speed, just that it toggles flash_mode_torch and flash_mode_off repeatedly until the button is pressed again.
I have tried:
Using a handler
Creating a separate class
The separate class containing the handler did not work because there was no intent in the main activity to launch or in the manifest because the code for it is not finished because I want to ask here how its done in the most simplest manner possible.
StrobeLightConfig.java
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class StrobeLightConfig extends Activity {
boolean check = false;
Camera sandy;
StrobeRunner runner;
Thread bw;
ImageButton btnClick;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (ImageButton) findViewById(R.id.btnSwitch);
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
sandy = Camera.open();
if (sandy == null) {
return;
}
sandy.release();
} catch (RuntimeException ex) {
return;
}
}
bw = new Thread(runner);
bw.start();
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (check) {
bw = new Thread(runner);
bw.start();
check = false;
} else {
check = true;
runner.requestStop = true;
}
}
});
final SeekBar skbar = (SeekBar) findViewById(R.id.SeekBar01);
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = 101 - progress;
runner.delayoff = 101 - progress;
}
});
}
#Override
protected void onStop() {
// runner.requestStop = true;
super.onStop();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(startMain);
}
}
StrobeRunner.java
import android.hardware.Camera;
public class StrobeRunner implements Runnable {
protected StrobeRunner()
{
}
public static StrobeRunner getInstance()
{
return ( instance == null ? instance = new StrobeRunner() : instance );
}
private static StrobeRunner instance;
public volatile boolean requestStop = false;
public volatile boolean isRunning = false;
public volatile int delay = 10;
public volatile int delayoff = 500;
public volatile StrobeLightConfig controller;
public volatile String errorMessage = "";
#Override
public void run() {
if(isRunning)
return;
requestStop=false;
isRunning = true;
Camera cam = Camera.open();
Camera.Parameters pon = cam.getParameters(), poff = cam.getParameters();
pon.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
poff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
while(!requestStop)
{
try{
cam.setParameters(pon);
Thread.sleep(delay);
cam.setParameters(poff);
Thread.sleep(delayoff);
}
catch(InterruptedException ex)
{
}
catch(RuntimeException ex)
{
requestStop = true;
errorMessage = "Error setting camera flash status. Your device may be unsupported.";
}
}
cam.release();
isRunning = false;
requestStop=false;
controller.mHandler.post(controller.mShowToastRunnable);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:progress="0"
android:layout_alignParentTop="true"
>
</SeekBar>
<ImageButton
android:id="#+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/w_led_on"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
</RelativeLayout>

Categories