Android-camera

提供:Dev Guides
移動先:案内検索

Android-カメラ

これらは、アプリケーションでカメラを使用できる次の2つの方法です。

  • アプリケーションで既存のAndroidカメラアプリケーションを使用する *アプリケーションでAndroidが提供するCamera APIを直接使用する

アプリケーションで既存のAndroidカメラアプリケーションを使用する

MediaStore.ACTION_IMAGE_CAPTUREを使用して、携帯電話にインストールされている既存のカメラアプリケーションを起動します。 その構文は以下のとおりです

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

上記とは別に、MediaStoreが提供する他の利用可能なインテントがあります。 それらは次のようにリストされています

Sr.No Intent type and description
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)

このメソッドは activity クラスで定義されています。 私たちはそれを主な活動から呼んでいます。 アクティビティクラスには、同じジョブを実行するメソッドが定義されていますが、アクティビティからではなく、他の場所から呼び出しているときに使用されます。 それらは以下にリストされています

Sr.No Activity function description
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_をオーバーライドすることで取得できます。

既存のカメラアプリケーションを起動して画像をキャプチャし、結果をビットマップの形式で表示する方法を示す例を次に示します。

この例を試すには、カメラがサポートされている実際のデバイスでこれを実行する必要があります。

Steps Description
1 You will use Android studio IDE to create an Android application and name it as Camera under a com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add intent code to launch the Camera.
3 Modify layout XML file res/layout/activity_main.xml
4 Add the Camera permission and run the application and choose a running android device and install the application on it and verify the results.

以下は、変更されたメインアクティビティファイル* 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>

以下は、1つの新しい定数を定義する 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からアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像の実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 アプリケーションを開始する前に、Androidスタジオは次のウィンドウを表示して、Androidアプリケーションを実行するオプションを選択します。

Androidカメラチュートリアル

オプションとしてモバイルデバイスを選択し、カメラを開いて次の画面を表示するモバイルデバイスを確認します-

Androidカメラチュートリアル