Você está na página 1de 12

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

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

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

MainActivity.java code:
package com.example.philipgo.flashlightapp;
//Dont forget about these import statements. They enable you to refer to
the different classes available in Android
import
import
import
import
import
import

android.content.Context;
android.graphics.PixelFormat;
android.os.SystemClock;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.app.Activity;

import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.AlertDialog;
android.content.DialogInterface;
android.content.pm.PackageManager;
android.hardware.Camera;
android.hardware.Camera.Parameters;
android.os.Bundle;
android.util.Log;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.widget.Button;
android.view.SurfaceHolder.Callback;
android.widget.TextView;
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;
}

//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 phones 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 phones 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;
}
}

@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) {
}

@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 phones 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>

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.

Flashlight Shake App Layout


Flashlight App = Text
OFF/ON = Text (name set to status)
Philip Nathaniel Go BSCpE 4 = Text

MainActivity.Java code:
package com.example.philipgo.flashlightapp;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.content.Context;
android.graphics.PixelFormat;
android.os.SystemClock;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.app.Activity;
android.app.AlertDialog;
android.content.DialogInterface;
android.content.pm.PackageManager;
android.hardware.Camera;
android.hardware.Camera.Parameters;
android.os.Bundle;
android.util.Log;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.widget.Button;

import
import
import
import
import
import
import

android.view.SurfaceHolder.Callback;
android.hardware.SensorEventListener;
android.hardware.Sensor;
android.hardware.SensorEvent;
android.hardware.SensorManager;
android.widget.TextView;
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.");

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()
{

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();

10

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;

11

}
}

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>

12

Você também pode gostar