12
1 La Salle University College of Engineering and Architecture Ozamiz City Software Engineering Project Basic Android App Using Android Studio School Year 2015-2016 By Philip Nathaniel Go, BSCpE – 4

Android Studio Flashlight App Basic

  • Upload
    philip

  • View
    23

  • Download
    0

Embed Size (px)

DESCRIPTION

Tutorial on how to make a flashlight app in Android Studio

Citation preview

Page 1: Android Studio Flashlight App Basic

1

La Salle University

College of Engineering and Architecture

Ozamiz City

Software Engineering Project

Basic Android App Using Android Studio

School Year 2015-2016

By Philip Nathaniel Go, BSCpE – 4

Page 2: Android Studio Flashlight App Basic

2

I. Software and Hardware Requirements

1. Android Studio (can be downloaded for free at

http://developer.android.com/sdk/index.html)

2. Android phone (A Nexus 5 was used for this project)

II. Flashlight Code

MainActivity.java code:

package com.example.philipgo.flashlightapp;

//Don’t forget about these import statements. They enable you to refer to

the different classes available in Android

import android.content.Context;

import android.graphics.PixelFormat;

import android.os.SystemClock;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.app.Activity;

Flashlight App layout

Turn ON = Button (name set to flash_on)

Turn OFF = Button (name set to flash_off)

Flashlight App = Text

© Philip Nathaniel Go – BSCpE – 4 = Text

Page 3: Android Studio Flashlight App Basic

3

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.pm.PackageManager;

import android.hardware.Camera;

import android.hardware.Camera.Parameters;

import android.os.Bundle;

import android.util.Log;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.view.View;

import android.widget.Button;

import android.view.SurfaceHolder.Callback;

import android.widget.TextView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements

SurfaceHolder.Callback, SensorEventListener {

Button flash_on;

Button flash_off;

private Camera camera;

private boolean isFlashOn;

private boolean hasFlash;

Parameters params;

SurfaceView preview; //SurfaceView is required in order for this app to

SurfaceHolder mholder; //work on a Nexus device

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

preview = (SurfaceView) findViewById(R.id.preview);

mholder = preview.getHolder();

mholder.addCallback(this);

flash_on = (Button) findViewById(R.id.flash_on);

flash_off = (Button) findViewById(R.id.flash_off);

hasFlash =

getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.

FEATURE_CAMERA_FLASH);

if(!hasFlash) //this statement checks whether the device has

{ //a flashlight or not

AlertDialog alert = new

AlertDialog.Builder(MainActivity.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) {

finish();

}

});

alert.show();

return;

}

Page 4: Android Studio Flashlight App Basic

4

//the code below sets what happens when the user presses the turn on button

flash_on.setOnClickListener(new View.OnClickListener()

{

@Override

public void onClick(View v)

{

turnOnFlash();

}

});

//the code below sets what happens when the user presses the turn off button

flash_off.setOnClickListener(new View.OnClickListener()

{

@Override

public void onClick(View v)

{

turnOffFlash();

}

});

}

//turnOnFlash() contains the code needed to turn the phone’s flashlight on

private void turnOnFlash()

{

if(!isFlashOn)

{

if(camera == null || params == null)

return;

try {

camera.setPreviewDisplay(mholder);

} catch (IOException e) {

e.printStackTrace();

}

params = camera.getParameters();

params.setFlashMode(Parameters.FLASH_MODE_TORCH);

camera.setParameters(params);

camera.startPreview();

isFlashOn = true;

}

}

//turnOffFlash() contains the code needed to turn the phone’s flashlight off

private void turnOffFlash()

{

if(isFlashOn)

{

if(camera == null || params == null)

return;

params = camera.getParameters();

params.setFlashMode(Parameters.FLASH_MODE_OFF);

camera.setParameters(params);

camera.stopPreview();

isFlashOn = false;

}

}

Page 5: Android Studio Flashlight App Basic

5

@Override

protected void onDestroy()

{

super.onDestroy();

}

@Override

protected void onPause()

{

super.onPause();

turnOffFlash();

//turns off the flashlight when the application is paused

}

@Override

protected void onRestart()

{

super.onRestart();

}

@Override

protected void onResume()

{

super.onResume();

}

@Override

protected void onStart()

{

super.onStart();

getCamera();

}

@Override

protected void onStop()

{

super.onStop();

if(camera != null)

{

camera.release();

camera = null;

}

}

@Override

public void surfaceCreated(SurfaceHolder holder) {

mholder = holder;

try {

camera.setPreviewDisplay(holder);

} catch (IOException e) {

e.printStackTrace();

}

}

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width,

int height) {

}

Page 6: Android Studio Flashlight App Basic

6

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

holder = null;

}

}

AndroidManifest.xml Code:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.philipgo.flashlightapp">

//The permission statements below enable you to use the phone’s various

hardware, which in this case is the camera

<uses-feature android:name="android.hardware.camera"

android:required="false" />

<uses-feature android:name="android.hardware.camera.flash"

android:required="false" />

<uses-permission android:name="android.hardware.camera.flash"/>

<uses-permission android:name="android.permission.CAMERA" />

<application

android:allowBackup="true"

android:icon="@mipmap/icon"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme"

android:screenOrientation="portrait"> //disables landscape mode

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Page 7: Android Studio Flashlight App Basic

7

III. Extra Feature (Shake to turn on flashlight)

You can also use a shake gesture to turn on the flashlight on. The only thing you need to

do is add some code for the accelerometer in addition to the existing code for the original

flashlight application.

MainActivity.Java code:

package com.example.philipgo.flashlightapp;

import android.content.Context;

import android.graphics.PixelFormat;

import android.os.SystemClock;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.pm.PackageManager;

import android.hardware.Camera;

import android.hardware.Camera.Parameters;

import android.os.Bundle;

import android.util.Log;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.view.View;

import android.widget.Button;

Flashlight Shake App Layout

Flashlight App = Text

OFF/ON = Text (name set to status)

© Philip Nathaniel Go – BSCpE – 4 = Text

Page 8: Android Studio Flashlight App Basic

8

import android.view.SurfaceHolder.Callback;

import android.hardware.SensorEventListener;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorManager;

import android.widget.TextView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements

SurfaceHolder.Callback, SensorEventListener {

private Camera camera;

private boolean isFlashOn;

private boolean hasFlash;

Parameters params;

SurfaceView preview;

SurfaceHolder mholder;

// Variables for accelerometer sensor

private SensorManager senSensorManager;

private Sensor senAccelerometer;

private long lastUpdate = 0;

private float last_x, last_y, last_z;

private static final int SHAKE_THRESHOLD = 1900;

//Change the shake_threshold to change the sensitivity of the device to

movements. Higher number = higher sensitivity and vice versa

TextView status;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

preview = (SurfaceView) findViewById(R.id.preview);

mholder = preview.getHolder();

mholder.addCallback(this);

hasFlash =

getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.

FEATURE_CAMERA_FLASH);

//Accelerometer variables initialization

senSensorManager = (SensorManager)

getSystemService(Context.SENSOR_SERVICE);

senAccelerometer =

senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

senSensorManager.registerListener(this, senAccelerometer,

SensorManager.SENSOR_DELAY_NORMAL);

status = (TextView)findViewById(R.id.textView3);

if(!hasFlash)

{

AlertDialog alert = new

AlertDialog.Builder(MainActivity.this).create();

alert.setTitle("Error");

alert.setMessage("Sorry, your device doesn't support flash

light.");

Page 9: Android Studio Flashlight App Basic

9

alert.setButton("Ok", new DialogInterface.OnClickListener(){

public void onClick(DialogInterface dialog, int which) {

finish();

}

});

alert.show();

return;

}

}

@Override

public void onSensorChanged(SensorEvent sensorEvent)

{

Sensor mySensor = sensorEvent.sensor;

//Tests if the device has an accelerometer. If it does, it proceeds

//to execute the code inside the if statement below.

if(mySensor.getType() == Sensor.TYPE_ACCELEROMETER)

{

//the values obtained from the accelerometer are stored in an array

//of floating values

float x = sensorEvent.values[0];

float y = sensorEvent.values[1];

float z = sensorEvent.values[2];

long curTime = System.currentTimeMillis();

if((curTime - lastUpdate) > 100)

{

long diffTime = curTime - lastUpdate;

lastUpdate = curTime;

float speed = Math.abs(x + y + z)/diffTime * 10000;

//turns the flashlight on/off if the speed exceeds the threshold

//value you set earlier.

if(speed > SHAKE_THRESHOLD)

{

if(!isFlashOn)

{

turnOnFlash(); //turns on flash

}

else

{

turnOffFlash(); //turns off flash

}

}

x = 0; //resets the value of the x, y, z back to zero

y = 0;

z = 0;

}

}

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy)

{

}

private void getCamera()

{

Page 10: Android Studio Flashlight App Basic

10

if(camera == null)

{

try

{

camera = Camera.open();

params = camera.getParameters();

}

catch(RuntimeException e)

{

Log.e("Camera Error.: ", e.getMessage());

}

}

}

private void turnOnFlash()

{

if(!isFlashOn)

{

if(camera == null || params == null)

return;

try {

camera.setPreviewDisplay(mholder);

} catch (IOException e) {

e.printStackTrace();

}

params = camera.getParameters();

params.setFlashMode(Parameters.FLASH_MODE_TORCH);

camera.setParameters(params);

camera.startPreview();

isFlashOn = true;

status.setText("ON");

}

}

private void turnOffFlash()

{

if(isFlashOn)

{

if(camera == null || params == null)

return;

params = camera.getParameters();

params.setFlashMode(Parameters.FLASH_MODE_OFF);

camera.setParameters(params);

camera.stopPreview();

isFlashOn = false;

status.setText("OFF");

}

}

@Override

protected void onDestroy()

{

super.onDestroy();

}

@Override

protected void onPause()

{

super.onPause();

Page 11: Android Studio Flashlight App Basic

11

senSensorManager.unregisterListener(this);

//unregisters the sensor when the application is paused. This saves battery.

turnOffFlash();

}

@Override

protected void onRestart()

{

super.onRestart();

}

@Override

protected void onResume()

{

super.onResume();

senSensorManager.registerListener(this, senAccelerometer,

SensorManager.SENSOR_DELAY_NORMAL);

//registers the sensor again upon resuming the application

}

@Override

protected void onStart()

{

super.onStart();

getCamera();

}

@Override

protected void onStop()

{

super.onStop();

if(camera != null)

{

camera.release();

camera = null;

}

}

@Override

public void surfaceCreated(SurfaceHolder holder) {

mholder = holder;

try {

camera.setPreviewDisplay(holder);

} catch (IOException e) {

e.printStackTrace();

}

}

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width,

int height) {

}

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

holder = null;

Page 12: Android Studio Flashlight App Basic

12

}

}

AndroidManifest.xml code:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.philipgo.flashlightapp">

<uses-feature android:name="android.hardware.camera"

android:required="false" />

<uses-feature android:name="android.hardware.camera.flash"

android:required="false" />

<uses-permission android:name="android.hardware.camera.flash"/>

<uses-permission android:name="android.permission.CAMERA" />

<application

android:allowBackup="true"

android:icon="@mipmap/icon"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme"

android:screenOrientation="portrait">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>