- Android 基础
- Android - 首页
- Android - 概述
- Android - 环境设置
- Android - 架构
- Android - 应用程序组件
- Android - Hello World 示例
- Android - 资源
- Android - 活动
- Android - 服务
- Android - 广播接收器
- Android - 内容提供程序
- Android - 碎片
- Android - 意图/过滤器
- Android - 用户界面
- Android - UI 布局
- Android - UI 控件
- Android - 事件处理
- Android - 样式和主题
- Android - 自定义组件
- Android 高级概念
- Android - 拖放
- Android - 通知
- 基于位置的服务
- Android - 发送电子邮件
- Android - 发送短信
- Android - 打电话
- 发布 Android 应用程序
- Android 有用示例
- Android - 警报对话框
- Android - 动画
- Android - 音频捕获
- Android - AudioManager
- Android - 自动完成
- Android - 最佳实践
- Android - 蓝牙
- Android - 相机
- Android - 剪贴板
- Android - 自定义字体
- Android - 数据备份
- Android - 开发者工具
- Android - 模拟器
- Android - Facebook 集成
- Android - 手势
- Android - Google 地图
- Android - 图像特效
- Android - ImageSwitcher
- Android - 内部存储
- Android - JetPlayer
- Android - JSON 解析器
- Android - Linkedin 集成
- Android - 加载微调器
- Android - 本地化
- Android - 登录屏幕
- Android - MediaPlayer
- Android - 多点触控
- Android - 导航
- Android - 网络连接
- Android - NFC 指南
- Android - PHP/MySQL
- Android - 进度圆圈
- Android - 进度条
- Android - 推送通知
- Android - RenderScript
- Android - RSS 阅读器
- Android - 屏幕录制
- Android - SDK 管理器
- Android - 传感器
- Android - 会话管理
- Android - 共享首选项
- Android - SIP 协议
- Android - 拼写检查器
- Android - SQLite 数据库
- Android - 支持库
- Android - 测试
- Android - 文字转语音
- Android - TextureView
- Android - Twitter 集成
- Android - UI 设计
- Android - UI 模式
- Android - UI 测试
- Android - WebView 布局
- Android - Wi-Fi
- Android - 小部件
- Android - XML 解析器
- Android 有用资源
- Android - 问答
- Android - 有用资源
- Android - 讨论
Android - 相机
以下两种方法可以在应用程序中使用相机
在应用程序中使用现有的 Android 相机应用程序
在应用程序中直接使用 Android 提供的 Camera API
在应用程序中使用现有的 Android 相机应用程序
您将使用 MediaStore.ACTION_IMAGE_CAPTURE 启动手机上安装的现有相机应用程序。其语法如下所示
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
除了上述内容外,MediaStore 还提供了其他可用的意图。它们列出如下
| 序号 | 意图类型和描述 |
|---|---|
| 1 |
ACTION_IMAGE_CAPTURE_SECURE 当设备处于安全状态时,它会返回从相机捕获的图像 |
| 2 |
ACTION_VIDEO_CAPTURE 它调用 Android 中现有的视频应用程序来捕获视频 |
| 3 |
EXTRA_SCREEN_ORIENTATION 它用于将屏幕方向设置为垂直或横向 |
| 4 |
EXTRA_FULL_SCREEN 它用于控制 ViewImage 的用户界面 |
| 5 |
INTENT_ACTION_VIDEO_CAMERA 此意图用于以视频模式启动相机 |
| 6 |
EXTRA_SIZE_LIMIT 它用于指定视频或图像捕获大小的大小限制 |
现在,您将使用函数 startActivityForResult() 启动此活动并等待其结果。其语法如下所示
startActivityForResult(intent,0)
此方法已在活动类中定义。我们从主活动中调用它。活动类中定义了一些执行相同工作的函数,但在您不是从活动而是从其他地方调用时使用。它们列出如下
| 序号 | 活动函数描述 |
|---|---|
| 1 |
startActivityForResult(Intent intent, int requestCode, Bundle options) 它启动一个活动,但可以随它一起携带额外的选项包 |
| 2 |
startActivityFromChild(Activity child, Intent intent, int requestCode) 当您的活动是其他任何活动的子活动时,它会启动该活动 |
| 3 |
startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) 它的工作方式与上面相同,但它可以随它一起携带捆绑形式的额外值 |
| 4 |
startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) 它从您当前所在的片段启动活动 |
| 5 |
startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options) 它不仅从片段启动活动,还可以随它一起携带额外值 |
无论您使用哪个函数启动活动,它们都会返回结果。可以通过覆盖函数 onActivityResult 获取结果。
示例
以下是一个示例,演示如何启动现有的相机应用程序以捕获图像并以位图形式显示结果。
要尝试此示例,您需要在支持相机的实际设备上运行它。
| 步骤 | 描述 |
|---|---|
| 1 | 您将使用 Android Studio IDE 创建一个 Android 应用程序,并在 com.example.sairamkrishna.myapplication 下将其命名为 Camera。 |
| 2 | 修改 src/MainActivity.java 文件以添加启动相机的意图代码。 |
| 3 | 修改布局 XML 文件 res/layout/activity_main.xml |
| 4 | 添加相机权限并运行应用程序,选择正在运行的 Android 设备并在其上安装应用程序并验证结果。 |
以下是修改后的主活动文件 src/MainActivity.java 的内容。
package com.example.sairamkrishna.myapplication;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
public static final String ALLOW_KEY = "ALLOWED";
public static final String CAMERA_PREF = "camera_pref";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (getFromPref(this, ALLOW_KEY)) {
showSettingsAlert();
} else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
showAlert();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
} else {
openCamera();
}
}
public static void saveToPreferences(Context context, String key, Boolean allowed) {
SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(key, allowed);
prefsEditor.commit();
}
public static Boolean getFromPref(Context context, String key) {
SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
return (myPrefs.getBoolean(key, false));
}
private void showAlert() {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
alertDialog.show();
}
private void showSettingsAlert() {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startInstalledAppDetailsActivity(MainActivity.this);
}
});
alertDialog.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
boolean
showRationale =
ActivityCompat.shouldShowRequestPermissionRationale(
this, permission);
if (showRationale) {
showAlert();
} else if (!showRationale) {
// user denied flagging NEVER ASK AGAIN
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
saveToPreferences(MainActivity.this, ALLOW_KEY, true);
}
}
}
}
// other 'case' lines to check for other
// permissions this app might request
}
}
@Override
protected void onResume() {
super.onResume();
}
public static void startInstalledAppDetailsActivity(final Activity context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
private void openCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
以下是 res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
</RelativeLayout>
以下是 res/values/strings.xml 的内容,用于定义一个新的常量
<resources> <string name="app_name">My Application</string> </resources>
以下是 AndroidManifest.xml 的默认内容:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开项目的一个活动文件,然后从工具栏中单击运行
图标。在启动应用程序之前,Android Studio 将显示以下窗口,以选择要在其中运行 Android 应用程序的选项。
选择您的移动设备作为选项,然后检查您的移动设备,它将打开相机并显示以下屏幕:
