Tuesday, 26 July 2016

FlashLight Example


Screenshots :



activity_main.xml :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ToggleButton
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:textSize="20dp"
        android:text="New ToggleButton"
        android:id="@+id/toggleButton"
        android:textColor="#ffffff"
        android:background="#057CA6"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


colors.xml :


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#047AA0</color>
    <color name="colorPrimaryDark">#03597A</color>
    <color name="colorAccent">#FF4081</color>
    <color name="red">#FF5500</color>
    <color name="white">#FFffff</color>
</resources>


MainActivity.java :


package com.chantisandroid.flashlight;

import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    ToggleButton toggleButton;
    Camera camera;
    Parameters parameters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        toggleButton.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        if (toggleButton.isChecked()) {
            camera = Camera.open();
            parameters = camera.getParameters();
            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(parameters);
            Toast.makeText(this,"FlashLight is On",Toast.LENGTH_LONG).show();
            toggleButton.setTextColor(getResources().getColor(R.color.red));

        } else {

            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(parameters);
            camera.release();
            camera = null;
            Toast.makeText(this, "FlashLight is Off", Toast.LENGTH_LONG).show();
            toggleButton.setTextColor(getResources().getColor(R.color.white));
        }
    }
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }
}




No comments:

Post a Comment

Alarm Manager Example in Android