Android相机

2022-10-13  本文已影响0人  BlueSocks

以下是您可以在应用程序中使用相机的两种方式:

1、在我们的应用程序中使用现有的Android相机应用程序
2、在我们的应用程序中直接使用安卓提供的相机API

在我们的应用程序中使用现有的Android相机应用程序

您将使用MediaStore.ACTION_IMAGE_CAPTURE启动手机上安装的现有相机应用程序。它的语法如下

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

除上述内容外,媒体商店还提供了其他可用的意图。它们如下所示

现在,您将使用函数启动此活动并等待其结果。它的语法如下

startActivityForResult(intent,0)

此方法已在活动类中定义。我们从主要活动中调用它。在活动类中定义了一些执行相同工作的方法,但是当您不是从活动而是从其他地方调用时使用。

无论您使用哪个函数来启动活动,它们都会返回结果。可以通过重写活动搜索结果上的函数来获得结果。

下面的示例演示如何启动现有的相机应用程序来捕获图像并以位图的形式显示结果。

步骤:
1、您将使用安卓工作室IDE创建一个安卓应用程序,并将其命名为相机。
2、修改 src/主活动.java文件以添加意图代码以启动摄像机。
3、修改布局 XML 文件分辨率/布局/activity_main.xml
4、添加相机权限并运行应用程序,然后选择正在运行的Android设备,并在其上安装应用程序并验证结果。
以下是已修改的主活动文件 src/主活动.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/布局/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/值/字符串的内容.xml定义一个新常量

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是安卓智能体的默认内容.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>

开始运行您的应用程序。

上一篇下一篇

猜你喜欢

热点阅读