您的位置:首页 > 移动开发 > Android开发

使用 Camera2 API 实现 Android 手电筒应用

2016-10-12 00:00 1121 查看
本文由码农网 – 小峰原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划

在本文中,我们将介绍如何创建Android免费手电筒应用程序。此教程是“Learn By Doing”教程系列的一部分,在这里我们将向你展示如何创建简单的Android app。这将会帮助Android开发新手增加经验。在学习了本教程之后,你就可以为Android手机创建最好的手电筒app,并通过Google play散播开来。

要下载完整的源代码,请访问以下链接,并在点击Download Now按钮来下载app apk,请访问以下链接并点击Download APK按钮:

使用Camera2 API的Android手电筒应用程序教程

我们希望你已经安装了Android Studio。如果还没有,那么按照教程安装Android Studio,然后再回到这里。也可以在阅读本教程之前,建议你先做一个简单的Hello World app,并在智能手机上运行。你可以学习如何连接,如何在实体Android设备上配置应用,以及如何通过Android Studio运行Hello World程序。好了,现在让我们开始创建我们的LED手电筒应用程序吧。首先通过如下方式在Android Studio中创建一个新项目。

创建新项目

请按照下列步骤做:







打开Android Studio,通过File => New => New Project创建一个新项目。输入应用程序名称为LedFlashLight和你公司的域名。(我们使用的是我们公司的域名,即androidtutorialpoint.com。同样,你可以使用你公司的。)

点击Next,选择Minimum SDK。保持默认设置,然后单击Next。

选择Empty Activity,然后单击Next。

在接下来的屏幕中,输入Empty Activity为FlashLightActivity,不要忘记查看Generate Layout Button按钮,然后单击Finish。



Gradle会同步项目和解决所有的依赖。

添加权限使用Camera和FlashLight

打开AndroidManifest.xml文件并添加以下权限:

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

这些uses-permissions标签告诉Android操作系统,我们的app需要访问
CAMERA
 和FLASHLIGHT。同样uses-feature告诉了在app中将使用什么功能。

LED Flash Light应用程序只能在人像模式下工作,因此添加下面的代码到
activity
 标签。

android:screenOrientation="portrait"

完整的AndroidManifest.xml如下:

AnroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtutorialpoint.ledflashlight" >
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.FLASHLIGHT" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.flash" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".FlashLightActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

除了软件包的名称,其他一切应该都和你的一样。

生成应用程序布局

打开activity_flash_light.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.camera2.MainActivity"
android:background="#000"
android:gravity="center">

<ImageButton
android:layout_gravity="center"
android:id="@+id/button_on_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/off"/>

</LinearLayout>

我们正在使用ImageButton。当用户按下此按钮时,LED手电筒将被切换。

如果你还是Android开发新手,那么可以通过下面的教程来了解更多关于Android布局的基础。

添加功能

打开FlashLightActivity.java并声明下列变量。

FlashLightActivity.java

package com.androidtutorialpoint.ledflashlight;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

public class FlashLightActivity extends AppCompatActivity {

private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private Boolean isTorchOn;
private MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FlashLightActivity", "onCreate()");
setContentView(R.layout.activity_flash_light);
mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
isTorchOn = false;

在这里,我们只声明变量,并在onCreate()方法中设置活动布局。我们还从布局中引用了mTorchOnOffButton Button。后面我们会再具体谈一谈。这是我们将使用Camera2API,因为Camera API在Android中现在已经过时了。

我们需要检测设备是否具有手电筒。万一设备不支持手电筒,那么我们需要用警报消息来提醒用户。

添加下面的代码在上面的
FlashActivity
 活动代码的下面。

FlashLightActivity

Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

if (!isFlashAvailable) {

AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}

如果你的手机不支持相机闪光灯,那么你会得到以下错误。

按下OK按钮,应用程序会关闭。



接下来,我们把代码添加到onCreate()方法以获得CameraManager对象。然后,我们设置OnClickListener()来开/关LED手电筒应用的按钮。

在OnClickListener()中,我们检查手电筒当前是开启还是关闭的,然后我们调用turnOffFlashLight()来关闭闪光灯,在手电筒已经开启的情况下,以及调用turnOnFlashLight()来开启闪光灯,在手电筒当前是关闭的情况下。

mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}

mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

接下来,我们要添加turnOffFlashLight()和turnOnFlashLight()方法分别用于关闭和开启闪光灯。我们还要添加一个方法playOnOffSound给一个点击按钮的声音效果。

public void turnOnFlashLight() {

try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.on);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void turnOffFlashLight() {

try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.off);

}

} catch (Exception e) {
e.printStackTrace();
}
}

private void playOnOffSound(){

mp = MediaPlayer.create(FlashLightActivity.this, R.raw.flash_sound);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}

在turnOffFlashLight()中,我们通过设置mCameraManager.setTorchMode(mCameraId, false);关闭LED手电筒。同样的,在turnOnFlashLight()中,我们通过设置mCameraManager.setTorchMode(mCameraId, true);打开闪光灯。在playOnOffSound()中,我们使用MediaPlayer类的create()方法来发出点击的声音。

最后,通过添加以下代码覆盖Activity Lifecycle方法。当app被用户最小化时,我们会关闭闪光灯,但只要用户回到app,闪光灯又会恢复。

@Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}

@Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}

@Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}

现在,在实际设备上运行这个app,打开手电筒,然后用自己的手电筒应用程序在黑暗中找寻东西。你可以通过点击顶部的Download Now按钮下载Android手电筒app源代码。你也可以通过点击上面的Download APK下载上面的手电筒apk。

下一步??

我们将在Learn By Doing中涵盖更多的教程!如果大家有任何疑问或建议的话,请在下面留下评论。

要下载完整的源代码,可以访问以下链接,并点击Download Now按钮,要下载app apk,请访问链接并点击Download APK 按钮:

使用Camera2 API的Android手电筒应用程序教程

许可证

这篇文章,以及相关的源代码和文件许可发布遵循Code Project Open License (CPOL)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: