I have a Flashlight code that use two buttons (on_btn and off_btn) to turn on and turn off the Flashlight.
How can I associate them in a single button?
Very novice can you give elaborate suggestion please?
The code below is found from an answer: And it works for my mobile. But on the emulator it crashs while clicking on the button. Here is the cat-log https://dl.dropbox.com/u/15065300/logcat1.png
The line number 74 is: Parameters params = mCamera.getParameters();
Can anybody any suggestion please?
public class FlashLight extends Activity {
private final static String LOG_TAG = "FlashLight";
private Button mOnBtn;
private Camera mCamera;
private boolean isActive;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//this will be inside your onCreate...
mOnBtn = (Button) findViewById(R.id.on_btn);
mOnBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
flipSwitch();
processClick();
}
});
}
//these will be outside your onCreate
public void flipSwitch() {
isActive = !isActive;
}
#Override
protected void onResume() {
super.onResume();
try{
mCamera = Camera.open();
mCamera.startPreview();
Toast.makeText(getApplicationContext(),"Camera is present", Toast.LENGTH_LONG).show();
} catch( Exception e ){
Log.e(LOG_TAG, "Impossible d'ouvrir la camera");
}
}
#Override
protected void onPause() {
if( mCamera != null ){
mCamera.release();
mCamera = null;
}
super.onPause();
}
public void processClick() {
if(isActive) {
Parameters params = mCamera.getParameters();
params.set("flash-mode", "torch");
mCamera.setParameters( params );
mCamera.startPreview();
}
else {
Parameters params = mCamera.getParameters();
params.set("flash-mode", "off");
mCamera.setParameters( params );
mCamera.stopPreview();
}
}
}
use the button to flip a boolean value, and change your flashlight to go on and off accordingly.
private boolean isActive;
//this will be inside your onCreate...
button.setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
flipSwitch();
processClick();
}
}
//these will be outside your onCreate
public void flipSwitch() {
isActive = !isActive;
}
public void processClick() {
if(isActive) {
//button is clicked on
}
else {
//button is clicked off
}
}
You could always use the Toggle Button instead of two buttons. It's very "Android formal".
//Create a toggle button
ToggleButton tg = (ToggleButton) findviewbyId(R.id.togbut);
//Implement onClickListener
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v){
//Flip on or off
}
});
In the onClick() method, you can do what you need to do according to what your app is suppose to do when the button is on or off.
In the xml layout, you say what the toggle button says when it's on and off.
<ToggleButton
android:id="#+id/togbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Button On"
android:textOff="Button Off"
android:checked="true" />
When you click the toggle button, it will automatically change the text and toggle.
Here's a good example: http://www.mkyong.com/android/android-togglebutton-example/
Hope that helps!
Related
How can I keep the flashlight on in the background even when I switch to next activity or next application. Also my flashlight turns off automatically when I my screen locks and I want to keep my flash glowing even the screen locks.
This is my current code:
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedform);
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(SavedForm.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Error. Failed to Open", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(SavedForm.this, R.raw.flashoff);
}else{
mp = MediaPlayer.create(SavedForm.this, R.raw.flashon);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.button_on);
}else{
btnSwitch.setImageResource(R.drawable.button_off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOnFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOffFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
#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_savedform, 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;
}
if(id==android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
The best way to do is by Running a Background service that handles the Flashlight.
You need to put your FlashLight Start and Stop code inside the OnStart and onDestroy of the Service. That you need to do on your own
First of all create a class named FlashLightService that extends the Service
public class FlashLightService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
// Put Your Code To Start the FlashLight Over Here
}
#Override
public void onDestroy() {
// Put Your Code To Stop the FlashLight Over Here
}
Now from any Activity you can start and stop the Flashlight according to your need
To start The FlashLight
startService(new Intent(this, FlashLightService.class));
To stop the FlashLight
stopService(new Intent(this, FlashLightService.class));
Do not forget to mention this in your AndroidManifest.xml
Let me know if this works! :)
Remove these code or line.
`
#Override
protected void onStop() {
super.onStop();
// on stop release the camera`enter code here`
if (camera != null) {
camera.release();
camera = null;
}
`
It worked for me.
I am not an android expert but I would recommend,
run it as service or run it as singleton thread.
The flash depends on the camera. Your onStop method contains: camera.release() which will release the camera hardware overriding any other acquisition methods implemented.
You could use background service to control the camera hardware. Start it from an activity and stop the service when your app is closed.
This is my little test program. My problem is that from run() method I access to fields of wrong (old) Activity, which was destroyed after screen orientation changed. What's the way to handle this situation?
And, by the way, I must have my activity been recreated, because in real application I have different layouts for portrait and landscape modes!
public class MainActivity extends Activity {
private EditText edit;
private Button button;
private ProgressDialog progressDialog;
private boolean isLoginInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit_timer);
button = (Button) findViewById(R.id.btn_start);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (edit.getText().toString().length() == 0) throw new Exception();
long dTime = Long.parseLong(edit.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.this.isLoginInProgress = false;
progressDialog.dismiss();
}
}, dTime);
progressDialog.show();
isLoginInProgress = true;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "bad time value", Toast.LENGTH_SHORT).show();
}
}
});
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
if (savedInstanceState != null) { // activity is restarted
isLoginInProgress = savedInstanceState.getBoolean("fl_login");
edit.setText(savedInstanceState.getString("edit"));
}
if (isLoginInProgress) { // Show dialog again
progressDialog.show();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("fl_login", isLoginInProgress);
outState.putString("edit", edit.getText().toString());
}
#Override
public void onDestroy(){
super.onDestroy();
progressDialog.dismiss();
}
}
You Can Use Database(SQLITE) for Storing Your Values..
I am working with camera flashlight project.
It load on the emulator but when I click on the "On" button it has stopped unexpectedly. Here is the cat-log https://dl.dropbox.com/u/15065300/logcat1.png
Here is the code:
public class FlashLight extends Activity {
private final static String LOG_TAG = "FlashLight";
private Button mOnBtn;
private Camera mCamera;
private boolean isActive;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//this will be inside your onCreate...
mOnBtn = (Button) findViewById(R.id.on_btn);
mOnBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
flipSwitch();
processClick();
}
});
}
//these will be outside your onCreate
public void flipSwitch() {
isActive = !isActive;
}
#Override
protected void onResume() {
super.onResume();
try{
mCamera = Camera.open();
mCamera.startPreview();
Toast.makeText(getApplicationContext(),"Camera is present", Toast.LENGTH_LONG).show();
} catch( Exception e ){
Log.e(LOG_TAG, "Impossible d'ouvrir la camera");
}
}
#Override
protected void onPause() {
if( mCamera != null ){
mCamera.release();
mCamera = null;
}
super.onPause();
}
public void processClick() {
if(isActive) {
Parameters params = mCamera.getParameters();
params.set("flash-mode", "torch");
mCamera.setParameters( params );
mCamera.startPreview();
}
else {
Parameters params = mCamera.getParameters();
params.set("flash-mode", "off");
mCamera.setParameters( params );
mCamera.stopPreview();
}
}
}
You have a NullPointerException on line 74 of Flashlight.java in your code.
It's probably that mCamera or params is being used while it's value is null. Check the initializations/assignments to these values.
i have made a flashlight app and i want to try to make add-on to allow a strobe light feature.
I want to set it up on a different button thought, not the same one. i think i need to use a timer , but i have never used a timer because im new to java.
here is my code for the flashlight:
public class FlashLightActivity extends Activity {
private boolean isLighOn = false;
private Camera camera;
private Button button;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
});
}
}
You could use a Handler
public class Strobe extends Activity {
private LinearLayout mLinearLayout;
private Handler mHander = new Handler();
private boolean mActive = false;
private boolean mSwap = true;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mSwap) {
mLinearLayout.setBackgroundColor(Color.WHITE);
mSwap = false;
mHander.postDelayed(mRunnable, 20);
} else {
mLinearLayout.setBackgroundColor(Color.BLACK);
mSwap = true;
mHander.postDelayed(mRunnable, 100);
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLinearLayout = (LinearLayout) findViewById(R.id.strobe);
startStrobe();
}
private void startStrobe() {
mActive = true;
mHander.post(mRunnable);
}
}
Set a Theme to the Activity to make it full screen.
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
I have a button on my camera preview screen to toggle the camera's flash. The camera starts on auto-flash which works then when the button is pressed the flash turns off but when i try to turn the flash back on it doesn't turn on and i don't know why?
Log.d("flash",mCamera.getParameters().getFlashMode());
Displays on off and auto as i press it. But it doesn't turn back on. Here is my full code
public void flashPressed(View v)
{
ImageButton flashButton = (ImageButton)findViewById(R.id.flash);
Camera.Parameters myP = mCamera.getParameters();
if(flashOn == 0)
{
flashButton.setImageResource(R.drawable.device_access_flash_off);
myP.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
flashOn = 1;
}
else if(flashOn == 1)
{
myP.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
flashButton.setImageResource(R.drawable.device_access_flash_on);
flashOn=2;
}else{
myP.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
flashButton.setImageResource(R.drawable.device_access_flash_automatic);
flashOn =0;
}
mCamera.setParameters(myP);
Log.d("flash",mCamera.getParameters().getFlashMode());
}
This is how I used to create a Flash app.
public class Flash extends Activity {
boolean cameraOpened;
static Camera camFlash = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onPause() {
super.onPause();
if (camFlash != null) {
camFlash.stopPreview();
camFlash.release();
camFlash = null;
}
}
public void turnOnFlash(View view) {
if (camFlash == null) {
camFlash = Camera.open();
}
if (camFlash != null) {
Parameters params = camFlash.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camFlash.setParameters(params);
camFlash.startPreview();
camFlash.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
}
public void turnOffFlash(View view) {
if (camFlash != null) {
camFlash.stopPreview();
camFlash.release();
camFlash = null;
}
}
}
the methods turnOnFlash() and turnOffFlash are called from xml android:onClick.
To avoid this problem I just created a new camera each time the flash option changes