Androidアプリでプログラムからカメラを起動して写真を撮影する方法【Kotlin】
本記事では、Androidアプリからプログラムを使ってカメラを起動し、撮影した画像を画面に表示する方法を解説します。Kotlinによる実装例を、レイアウトXML・MainActivity・マニフェストファイルの順に、ステップごとにわかりやすく紹介していきます。
手順1:新規プロジェクトを作成する
Android Studioを開き、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力し、プロジェクトを完成させてください。
手順2:レイアウトファイル(res/layout/activity_main.xml)を編集する
以下のコードをactivity_main.xmlに追加します。このレイアウトには、操作を促すTextView、撮影した画像を表示するImageView、カメラを起動するためのButtonが配置されています。
サンプルコード
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/imageView"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp"
android:text="Click the below button to take photo from camera"
android:textAlignment="center"
android:textColor="@android:color/holo_purple"
android:textSize="16sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="630dp"
android:layout_above="@id/btnCaptureImage"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_baseline_image_24" />
<Button
android:id="@+id/btnCaptureImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Capture Image" />
</RelativeLayout>
手順3:MainActivity.ktを実装する
続いて、src/MainActivity.ktに以下のコードを追加します。ボタンがタップされるとカメラ権限をリクエストし、許可された場合はカメラアプリを起動します。撮影結果はonActivityResult()で受け取り、ImageViewに表示される仕組みです。
import android.Manifest
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
lateinit var button: Button
private lateinit var imageView: ImageView
lateinit var imageUri: Uri
private val permissionCode = 1000
private val imageCaptureCode = 1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
button = findViewById(R.id.btnCaptureImage)
button.setOnClickListener {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
permissionCode
)
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
openCamera()
} else {
PackageManager.PERMISSION_DENIED
}
}
}
private fun openCamera() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, imageCaptureCode)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String?>,
grantResults: IntArray
) {
when (requestCode) {
permissionCode -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera()
} else {
Toast.makeText(this, "Permission denied...", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
imageView.setImageURI(imageUri);
}
}
}
手順4:AndroidManifest.xmlに権限を追加する
カメラ機能と保存先としての外部ストレージへの書き込みを行うため、パーミッションの宣言が必要です。androidManifest.xmlに以下のコードを追加してください。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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>
アプリを実行して動作を確認する
それでは、実際にアプリを実行してみましょう。ここでは、実機のAndroidスマートフォンをパソコンに接続していることを前提とします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーにある「Run」アイコン
をクリックします。デバイス選択の候補から接続したスマートフォンを選ぶと、端末側にアプリの初期画面が表示されます。
注意:より正確な動作確認のため、必ず実機でテストすることをおすすめします。



-
Androidアプリでプログラムから着信に自動応答する方法を解説
この記事では、Androidアプリケーションからプログラムによって着信に自動応答する方法を、サンプルコードとともに段階的に解説します。電話機能を持つアプリや自動応答システムを開発したい方に役立つ内容です。 手順1:Android Studioで新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。 手順2:レイアウトファイル(activity_main.xml)を編集する res/layout/activity_main.xml に以下のコードを
-
【Android】プログラムでアプリケーションを終了する方法|finish()とSystem.exit(0)の使い方
はじめにこの記事では、Androidアプリをプログラム(コード)から終了させる方法を解説します。ボタンをタップするとアプリが終了するシンプルなサンプルアプリを通じて、実装手順をステップごとに見ていきましょう。ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。ステップ2:レイアウトファイルの編集res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、ガイダンス用のTextViewと、アプリを終了するためのB