Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jp.hyogo.fukusaki.town.yokai.view;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.app.Dialog;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.ImageFormat;
- import android.graphics.SurfaceTexture;
- import android.hardware.Sensor;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- import android.hardware.camera2.CameraAccessException;
- import android.hardware.camera2.CameraCaptureSession;
- import android.hardware.camera2.CameraCharacteristics;
- import android.hardware.camera2.CameraDevice;
- import android.hardware.camera2.CameraManager;
- import android.hardware.camera2.CameraMetadata;
- import android.hardware.camera2.CaptureRequest;
- import android.hardware.camera2.TotalCaptureResult;
- import android.hardware.camera2.params.StreamConfigurationMap;
- import android.location.Criteria;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.location.Location;
- import android.media.Image;
- import android.media.ImageReader;
- import android.media.MediaPlayer;
- import android.os.Environment;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.support.annotation.NonNull;
- import android.support.v4.app.ActivityCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.util.Size;
- import android.util.SizeF;
- import android.util.SparseIntArray;
- import android.view.Gravity;
- import android.view.LayoutInflater;
- import android.view.Surface;
- import android.view.TextureView;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.ListView;
- import android.widget.PopupWindow;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.bumptech.glide.Glide;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.nio.ByteBuffer;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Objects;
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.UUID;
- import io.realm.RealmResults;
- import jp.hyogo.fukusaki.town.yokai.R;
- import jp.hyogo.fukusaki.town.yokai.model.CatchItem;
- import jp.hyogo.fukusaki.town.yokai.model.Item;
- import jp.hyogo.fukusaki.town.yokai.model.Point;
- import jp.hyogo.fukusaki.town.yokai.model.Yokai;
- import jp.hyogo.fukusaki.town.yokai.utils.Constant;
- import jp.hyogo.fukusaki.town.yokai.utils.DeviceOrientation;
- import jp.hyogo.fukusaki.town.yokai.utils.ItemUtil;
- import jp.hyogo.fukusaki.town.yokai.utils.PowerPointJobUtil;
- import jp.hyogo.fukusaki.town.yokai.utils.StringUtil;
- import jp.hyogo.fukusaki.town.yokai.utils.YokaiUtil;
- public class CameraActivity extends AppCompatActivity {
- private static final long GPS_MIN_TIME = 1000;
- private static final float GPS_MIN_DISTANCE = 5; // unit: m
- private static final float RADIUS = 50; // unit: m
- private static final int SOUND = R.raw.item;
- public static final String CAMERA_FRONT = "1";
- public static final String CAMERA_BACK = "0";
- private static final String TAG = "CameraActivity";
- private static final String TAG_ERROR = "CameraActivity_Error";
- private static final int REQUEST_CAMERA_PERMISSION = 200;
- private static final int REQUEST_STORAGE_PERMISSION = 201;
- private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
- static {
- ORIENTATIONS.append(Surface.ROTATION_0, 90);
- ORIENTATIONS.append(Surface.ROTATION_90, 0);
- ORIENTATIONS.append(Surface.ROTATION_180, 270);
- ORIENTATIONS.append(Surface.ROTATION_270, 180);
- }
- private MediaPlayer mp = null;
- private Timer mTimerStartYelling = null;
- private Timer mTimerStopYelling = null;
- private TimerTask mTimerStartYellingTask = null;
- private TimerTask mTimerStopYellingTask = null;
- private CameraDevice cameraDevice;
- private String cameraDeviceID = CAMERA_FRONT;
- private CameraCaptureSession cameraCaptureSessions;
- private CaptureRequest.Builder captureRequestBuilder;
- private Size mImageDimension;
- private Context mContext;
- private TextureView mCameraViewPort;
- private TextureView.SurfaceTextureListener mCameraViewPortListener = new TextureView.SurfaceTextureListener() {
- @Override
- public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
- openCamera();
- }
- @Override
- public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
- // Transform you image captured size according to the surface width and height, và thay đổi kích thước ảnh
- }
- @Override
- public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
- return false;
- }
- @Override
- public void onSurfaceTextureUpdated(SurfaceTexture surface) {
- }
- };
- private ImageReader mImageReader;
- private File mFile;
- private Handler mBackgroundHandler;
- private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
- @Override
- public void onOpened(@NonNull CameraDevice camera) {
- // Camera opened
- cameraDevice = camera;
- createCameraPreview();
- }
- @Override
- public void onDisconnected(@NonNull CameraDevice camera) {
- cameraDevice.close();
- }
- @Override
- public void onError(@NonNull CameraDevice camera, int error) {
- cameraDevice.close();
- cameraDevice = null;
- }
- };
- private HandlerThread mBackgroundThread;
- private Item mSelectedItem;
- private Yokai mFoundYokai;
- private boolean mIsYelling = false;
- private boolean mIsCatching = false;
- private String mUsedItemID = "";
- private Dialog dialog;
- private RealmResults<Item> mItems;
- // private RealmResults<CatchItem> mCatchedItems;
- /* for device orientation */
- private DeviceOrientation deviceOrientationUtil;
- private SensorManager mSensorManager;
- private Sensor accelerometer;
- private Sensor magnetometer;
- private Sensor gyroscope;
- private SensorEventListener sensorEventListener;
- private LocationManager mLocationManager;
- private LocationListener mLocationListener;
- private Location mLocation;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- Log.d(TAG, "onCreate");
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_camera);
- mContext = this;
- mCameraViewPort = findViewById(R.id.texture);
- mCameraViewPort.setSurfaceTextureListener(mCameraViewPortListener);
- TextView redPoint = findViewById(R.id.point_red_text);
- TextView bluePoint = findViewById(R.id.point_blue_text);
- TextView greenPoint = findViewById(R.id.point_green_text);
- PowerPointJobUtil.updateViewPowerPoint(mContext, redPoint, bluePoint, greenPoint);
- //List item
- TextView showListItemButton = findViewById(R.id.txtListItem);
- showListItemButton.setOnClickListener(v -> showListItem());
- // capture
- ImageView captureButton = findViewById(R.id.btnCapture);
- captureButton.setOnClickListener(v -> {
- if (mFoundYokai != null) {
- if (!mIsCatching) {
- mIsCatching = true;
- takePicture();
- } else {
- Log.d(TAG, "Catching yokai...");
- }
- } else {
- Log.d(TAG, "No yokai found!");
- Toast.makeText(CameraActivity.this, "No yokai found", Toast.LENGTH_LONG).show();
- }
- });
- // switch camera
- ImageView switchCameraButton = findViewById(R.id.switch_camera);
- switchCameraButton.setOnClickListener(v -> switchCamera());
- // go to radarActivity
- ImageView goToRadarButton = findViewById(R.id.btn_radar);
- goToRadarButton.setOnClickListener(v -> {
- Intent goRadar = new Intent(CameraActivity.this, RadarActivity.class);
- startActivity(goRadar);
- });
- // back home
- TextView goHomeButton = findViewById(R.id.txtHome);
- goHomeButton.setOnClickListener(v -> {
- Intent backHome = new Intent(CameraActivity.this, HomeActivity.class);
- startActivity(backHome);
- });
- /* sensor */
- mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
- accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
- magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
- deviceOrientationUtil = new DeviceOrientation();
- sensorEventListener = deviceOrientationUtil.getEventListener();
- /* location */
- mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
- Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
- Log.d(TAG, "onCreate: ACCESS_FINE permission not granted");
- return;
- }
- mLocationListener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- /* get yokai */
- mLocation = location;
- findYokai(location);
- // mLocationManager.removeUpdates(this);
- }
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
- @Override
- public void onProviderEnabled(String provider) {
- }
- @Override
- public void onProviderDisabled(String provider) {
- }
- };
- String provider = mLocationManager.getBestProvider(new Criteria(), false);
- mLocation = (mLocation = mLocationManager.getLastKnownLocation(provider)) != null ? mLocation :
- (mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) != null ? mLocation :
- (mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) != null ? mLocation : null;
- // findYokai(mLocation);
- // dummy
- // YokaiUtil.dummyYokai(mLocation, 100);
- mItems = ItemUtil.getItems();
- }
- @Override
- protected void onResume() {
- Log.d(TAG, "onResume");
- super.onResume();
- mp = MediaPlayer.create(mContext, SOUND);
- if (mCameraViewPort.isAvailable()) {
- } else {
- mCameraViewPort.setSurfaceTextureListener(mCameraViewPortListener);
- }
- if (openCamera()) {
- startBackgroundThread();
- }
- }
- @Override
- protected void onPause() {
- Log.d(TAG, "onPause");
- super.onPause();
- stopBackgroundThread();
- }
- @Override
- protected void onStop() {
- Log.d(TAG, "onStop");
- super.onStop();
- stopBackgroundThread();
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == REQUEST_CAMERA_PERMISSION) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
- // close the app
- Toast.makeText(CameraActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
- finish();
- }
- }
- if (requestCode == REQUEST_STORAGE_PERMISSION) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
- // close the app
- Toast.makeText(CameraActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
- finish();
- }
- }
- }
- protected void startBackgroundThread() {
- Log.d(TAG, "startBackgroundThread");
- mBackgroundThread = new HandlerThread("Camera Background");
- mBackgroundThread.start();
- mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
- /* sensor */
- mSensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
- mSensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
- /* mLocation */
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
- Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
- Log.d(TAG, "onCreate: ACCESS_FINE permission not granted");
- return;
- }
- mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
- GPS_MIN_TIME, GPS_MIN_DISTANCE, mLocationListener);
- String provider = mLocationManager.getBestProvider(new Criteria(), false);
- mLocation = (mLocation = mLocationManager.getLastKnownLocation(provider)) != null ? mLocation :
- (mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) != null ? mLocation :
- (mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) != null ? mLocation : null;
- findYokai(mLocation);
- }
- protected void stopBackgroundThread() {
- Log.d(TAG, "stopBackgroundThread");
- try {
- if (mBackgroundThread != null) {
- mBackgroundThread.quitSafely();
- mBackgroundThread.join();
- mBackgroundThread = null;
- }
- mBackgroundHandler = null;
- /* sensor */
- mSensorManager.unregisterListener(deviceOrientationUtil.getEventListener());
- mSensorManager.unregisterListener(sensorEventListener);
- /* mLocation */
- mLocationManager.removeUpdates(mLocationListener);
- /* timer */
- stopTimer();
- } catch (InterruptedException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "stopBackgroundThread: general exception");
- }
- }
- private void stopTimer() {
- Log.d(TAG, "stopTimer");
- if (mp.isPlaying()) {
- mp.setLooping(false);
- mp.pause();
- }
- if (mTimerStartYellingTask != null) {
- mTimerStartYellingTask.cancel();
- mTimerStartYellingTask = null;
- }
- if (mTimerStopYellingTask != null) {
- mTimerStopYellingTask.cancel();
- mTimerStopYellingTask = null;
- }
- if (mTimerStartYelling != null) {
- mTimerStartYelling.cancel();
- mTimerStartYelling.purge();
- mTimerStartYelling = null;
- }
- if (mTimerStopYelling != null) {
- mTimerStopYelling.cancel();
- mTimerStopYelling.purge();
- mTimerStopYelling = null;
- }
- }
- private void previewItem(int itemTime, String itemURL) {
- if (itemURL == null || itemURL.isEmpty()) {
- Log.d(TAG, "previewItem: itemURL null or empty");
- return;
- }
- ImageView itemGifView = findViewById(R.id.active_item_gif);
- itemGifView.setVisibility(View.VISIBLE);
- Glide.with(this).load(itemURL).into(itemGifView);
- if (itemTime > -1) {
- /* off after interval */
- new android.os.Handler().postDelayed(
- () -> {
- mUsedItemID = null;
- itemGifView.setVisibility(View.GONE);
- }, itemTime * 1000);
- }
- }
- public void switchCamera() {
- if (cameraDeviceID.equals(CAMERA_FRONT)) {
- cameraDeviceID = CAMERA_BACK;
- closeCamera();
- openCamera(cameraDeviceID);
- Toast.makeText(CameraActivity.this, "Back camera", Toast.LENGTH_LONG).show();
- } else if (cameraDeviceID.equals(CAMERA_BACK)) {
- cameraDeviceID = CAMERA_FRONT;
- closeCamera();
- openCamera(cameraDeviceID);
- Toast.makeText(CameraActivity.this, "Front camera", Toast.LENGTH_LONG).show();
- }
- }
- private void calculateFOV(CameraManager cManager) {
- float horizonalAngle = 0;
- float verticalAngle = 0;
- try {
- for (final String cameraId : cManager.getCameraIdList()) {
- CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
- int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
- if (cOrientation == CameraCharacteristics.LENS_FACING_BACK) {
- float[] maxFocus = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS);
- SizeF size = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
- float w = size.getWidth();
- float h = size.getHeight();
- horizonalAngle = (float) (2 * Math.atan(w / (maxFocus[0] * 2)));
- verticalAngle = (float) (2 * Math.atan(h / (maxFocus[0] * 2)));
- }
- }
- Log.d("horizonalAngle", String.valueOf(horizonalAngle));
- Log.d("verticalAngle", String.valueOf(verticalAngle));
- } catch (CameraAccessException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "calculateFOV: general exception");
- }
- }
- protected void takePicture() {
- Log.e(TAG, "takePicture call");
- if (cameraDevice == null) {
- Log.e(TAG_ERROR, "takePicture: cameraDevice null");
- mIsCatching = false;
- return;
- }
- CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- calculateFOV(manager);
- try {
- Log.e(TAG, "takePicture try catch call");
- CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
- Size[] jpegSizes;
- jpegSizes = Objects.requireNonNull(characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)).getOutputSizes(ImageFormat.JPEG);
- // CAPTURE IMAGE with custom size
- int width = 640;
- int height = 480;
- if (jpegSizes != null && 0 < jpegSizes.length) {
- width = jpegSizes[0].getWidth();
- height = jpegSizes[0].getHeight();
- }
- ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
- List<Surface> outputSurfaces = new ArrayList<>(2);
- outputSurfaces.add(reader.getSurface());
- outputSurfaces.add(new Surface(mCameraViewPort.getSurfaceTexture()));
- final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
- captureBuilder.addTarget(reader.getSurface());
- captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
- // check orietation depend on each device
- int rotation = getWindowManager().getDefaultDisplay().getRotation();
- captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
- String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/camera_catch_yokai" + UUID.randomUUID().toString() + ".jpg";
- mFile = new File(filePath);
- String yokaiID = "";
- float mDirection = 0;
- float mYokaiDistance = 0;
- boolean isReleasedPower = false;
- if (mFoundYokai != null) {
- yokaiID = mFoundYokai.getYokaiId();
- if (mLocation != null) {
- mDirection = mLocation.bearingTo(YokaiUtil.getYokaiLocation(mFoundYokai));
- mYokaiDistance = YokaiUtil.getDistance(mLocation, mFoundYokai.getLocation());
- }
- isReleasedPower = PowerPointJobUtil.releasePower(mContext, mFoundYokai.getPoint());
- }
- if (mFoundYokai != null || isReleasedPower) {
- String finalYokaiID = yokaiID;
- float finalMDirection = mDirection;
- float finalMYokaiDistance = mYokaiDistance;
- ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
- @Override
- public void onImageAvailable(ImageReader reader) {
- try (Image image = reader.acquireLatestImage()) {
- ByteBuffer buffer = image.getPlanes()[0].getBuffer();
- byte[] bytes = new byte[buffer.capacity()];
- buffer.get(bytes);
- save(bytes);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: onImageAvailable file not found exception");
- } catch (IOException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: onImageAvailable general exception");
- } catch (Exception e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: Exception general");
- }
- }
- // Save image
- private void save(byte[] bytes) throws IOException {
- try (OutputStream output = new FileOutputStream(mFile)) {
- output.write(bytes);
- Intent intent = new Intent(getBaseContext(), YokaiCatchResultActivity.class);
- intent.putExtra(Constant.EXTRA_YOKAI_IMAGE_PATH, filePath);
- intent.putExtra(Constant.EXTRA_YOKAI_ID, finalYokaiID);
- intent.putExtra(Constant.EXTRA_YOKAI_POWER_REDUCED, 0);
- intent.putExtra(Constant.EXTRA_YOKAI_DISTANCE, finalMYokaiDistance);
- intent.putExtra(Constant.EXTRA_YOKAI_ANGLE, deviceOrientationUtil.checkAngle()); // 0 if |, 1 if /
- intent.putExtra(Constant.EXTRA_YOKAI_DIRECTION, deviceOrientationUtil.checkDirection(finalMDirection)); // true if direction
- intent.putExtra(Constant.EXTRA_YOKAI_USED_ITEM, mUsedItemID);
- intent.putExtra(Constant.EXTRA_YOKAI_YELLING, mIsYelling);
- startActivity(intent);
- // stopBackgroundThread();
- finish();
- } catch (Exception e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: save general exception");
- }
- }
- };
- reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
- cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
- @Override
- public void onConfigured(@NonNull CameraCaptureSession session) {
- try {
- // Capture by Pressing capture button
- CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
- @Override
- public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
- super.onCaptureCompleted(session, request, result);
- // Toast.makeText(CameraActivity.this, "Saved:" + mFile, Toast.LENGTH_SHORT).show();
- createCameraPreview();
- }
- };
- session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
- } catch (Exception e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: onConfigured camera access exception");
- }
- }
- @Override
- public void onConfigureFailed(@NonNull CameraCaptureSession session) {
- }
- }, mBackgroundHandler);
- } else {
- mIsCatching = false;
- Log.d(TAG, "takePicture: Not enough power");
- Toast.makeText(CameraActivity.this, "Not enough power!", Toast.LENGTH_SHORT).show();
- }
- Log.e(TAG, "takePicture try catch End");
- } catch (Exception e) {
- mIsCatching = false;
- e.printStackTrace();
- Log.e(TAG_ERROR, "takePicture: general exception");
- }
- Log.e(TAG, "takePicture End");
- }
- // init camera for preview in textureView
- protected void createCameraPreview() {
- try {
- SurfaceTexture texture = mCameraViewPort.getSurfaceTexture();
- if (texture != null) {
- texture.setDefaultBufferSize(mImageDimension.getWidth(), mImageDimension.getHeight());
- Surface surface = new Surface(texture);
- captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
- captureRequestBuilder.addTarget(surface);
- cameraDevice.createCaptureSession(Collections.singletonList(surface), new CameraCaptureSession.StateCallback() {
- @Override
- public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
- //The camera is already closed
- if (cameraDevice == null) {
- Log.d(TAG, "createCameraPreview: cameraDevice null");
- return;
- }
- // When the session is ready, we start displaying the preview.
- cameraCaptureSessions = cameraCaptureSession;
- updatePreview();
- }
- @Override
- public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
- // create a handler to post messages to the main thread
- Handler mHandler = new Handler(getMainLooper());
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(CameraActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
- }
- });
- }
- }, null);
- }
- } catch (CameraAccessException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "createCameraPreview: general exception");
- }
- }
- private boolean openCamera() {
- CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- try {
- cameraDeviceID = manager.getCameraIdList()[0];
- return openCamera(cameraDeviceID);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "openCamera: general exception");
- return false;
- }
- }
- private boolean openCamera(String cameraId) {
- CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- try {
- CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
- StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
- assert map != null;
- mImageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
- /* request permissions */
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(CameraActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
- Log.d(TAG, "openCamera: permission not granted");
- return false;
- }
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(CameraActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
- Log.d(TAG, "openCamera: permission not granted");
- return false;
- }
- manager.openCamera(cameraId, stateCallback, null);
- return true;
- } catch (CameraAccessException e) {
- e.printStackTrace();
- Log.e(TAG_ERROR, "openCamera: general exception");
- return false;
- }
- }
- protected void updatePreview() {
- if (cameraDevice == null) {
- Log.e(TAG_ERROR, "updatePreview: cameraDevice null");
- }
- captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
- try {
- cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
- } catch (CameraAccessException e) {
- Log.e(TAG_ERROR, "updatePreview: general exception");
- e.printStackTrace();
- }
- }
- private void closeCamera() {
- if (null != cameraDevice) {
- cameraDevice.close();
- cameraDevice = null;
- }
- if (null != mImageReader) {
- mImageReader.close();
- mImageReader = null;
- }
- Log.d(TAG, "Close camera");
- }
- public void showListItem() {
- dialog = new Dialog(CameraActivity.this);
- dialog.setTitle(R.string.item);
- dialog.setContentView(R.layout.activity_camera_dialog_item_list);
- final ListView lv = dialog.findViewById(R.id.lvItem);
- final Button btnCancel = dialog.findViewById(R.id.Cancel);
- Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
- ArrayList<String> arrItemNames = new ArrayList<>();
- for (Item item : mItems) {
- int count = 0;
- CatchItem mCaughtItem = ItemUtil.getCaughtItem(item);
- if (mCaughtItem != null) count = mCaughtItem.getCount();
- arrItemNames.add(item.getItemName() + ": " + String.valueOf(count));
- }
- ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, R.layout.activity_camera_item_list, R.id.txtItem, arrItemNames);
- lv.setAdapter(arrayAdapter);
- lv.setOnItemClickListener((parent, view, position, id) -> {
- dialog.dismiss();
- mSelectedItem = mItems.get(position);
- if (mSelectedItem == null) {
- Log.d(TAG, "showListItem: selected item null");
- return;
- }
- showDetailItem(mSelectedItem);
- });
- btnCancel.setOnClickListener(v -> dialog.dismiss());
- dialog.show();
- }
- private void findYokai(Location location) {
- if (location == null) {
- Log.d(TAG, "Location: null");
- Toast.makeText(CameraActivity.this, "Location not available", Toast.LENGTH_LONG).show();
- return;
- }
- Log.d(TAG, "findYokai in location: " + mLocation);
- mFoundYokai = YokaiUtil.getClosestActiveYokaiInRange(location, RADIUS);
- if (mFoundYokai != null) {
- Toast.makeText(CameraActivity.this, "Found yokai: " + mFoundYokai.getYokaiId(), Toast.LENGTH_LONG).show();
- Log.d(TAG, "Found yokai: " + mFoundYokai.getYokaiId());
- startYelling(mFoundYokai.getInterval());
- } else {
- Log.d(TAG, "No yokai found!");
- Toast.makeText(CameraActivity.this, "No yokai found", Toast.LENGTH_LONG).show();
- }
- }
- private void startYelling(String intervalStr) {
- int interval = StringUtil.stringToInt(intervalStr);
- if (interval > 0 && mFoundYokai != null) {
- String yokaiID = mFoundYokai.getYokaiId();
- String yokaiPos = mFoundYokai.getLocation().getLat() + ", " + mFoundYokai.getLocation().getLon();
- /* pause audio */
- mTimerStopYelling = new Timer();
- mTimerStopYellingTask = new TimerTask() {
- @Override
- public void run() {
- mp.pause();
- mIsYelling = false;
- Log.d("yokai stop yelling", "stop");
- }
- };
- mTimerStopYelling.scheduleAtFixedRate(mTimerStopYellingTask, interval * 1000, interval * 1000 + 2000);
- /* play */
- mTimerStartYelling = new Timer();
- mTimerStartYellingTask = new TimerTask() {
- @Override
- public void run() {
- if (mp == null) {
- mp = MediaPlayer.create(mContext, SOUND);
- }
- mp.setLooping(true);
- mp.start();
- // mp.setOnPreparedListener(mp -> mp.start());
- mIsYelling = true;
- Log.d("yokai start yelling " + yokaiID, yokaiPos);
- }
- };
- mTimerStartYelling.scheduleAtFixedRate(mTimerStartYellingTask, 50, interval * 1000 + 2000);
- }
- }
- private void showDetailItem(Item item) {
- if (item == null) {
- Log.d(TAG, "showDetailItem: selected item null");
- return;
- }
- dialog = new Dialog(CameraActivity.this);
- dialog.setContentView(R.layout.activity_camera_dialog_item_detail);
- final TextView itemDetailView = dialog.findViewById(R.id.txtItemDetail);
- itemDetailView.setText(item.getItemDescription());
- final TextView itemNameView = dialog.findViewById(R.id.txtItemName);
- itemNameView.setText(item.getItemName());
- final Button btnCancel = dialog.findViewById(R.id.btnExit);
- final Button btnUse = dialog.findViewById(R.id.btnUse);
- Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
- btnCancel.setOnClickListener(v -> dialog.dismiss());
- CatchItem mCatchItem = ItemUtil.getCaughtItem(item);
- boolean isUsable = mCatchItem != null && mCatchItem.getCount() >= 1;
- btnUse.setEnabled(isUsable);
- btnUse.setOnClickListener(v -> useItem(item, mCatchItem));
- dialog.show();
- }
- public void useItem(Item item, CatchItem finalMCatchItem) {
- dialog.dismiss();
- mUsedItemID = item.getItemId();
- int itemTime = StringUtil.stringToInt(item.getItemTime());
- if (itemTime > -1) {
- String itemURL = ItemUtil.getItemUrlByID(item.getItemId());
- previewItem(itemTime, itemURL);
- }
- ItemUtil.useItem(item);
- if (item.getItemId().equals(Constant.CHARGE_ITEM)) {
- if (finalMCatchItem == null) return;
- Point itemPoint = finalMCatchItem.getItemPoint();
- if (itemPoint == null) return;
- PowerPointJobUtil.doCharge(mContext, itemPoint);
- TextView redPoint = findViewById(R.id.point_red_text);
- TextView bluePoint = findViewById(R.id.point_blue_text);
- TextView greenPoint = findViewById(R.id.point_green_text);
- PowerPointJobUtil.updateViewPowerPoint(mContext, redPoint, bluePoint, greenPoint);
- String toastedStr = "";
- if (StringUtil.stringToInt(itemPoint.getFire()) > 0) {
- toastedStr += "+" + itemPoint.getFire() + "火";
- }
- if (StringUtil.stringToInt(itemPoint.getWater()) > 0) {
- toastedStr += " +" + itemPoint.getWater() + "水";
- }
- if (StringUtil.stringToInt(itemPoint.getWind()) > 0) {
- toastedStr += " +" + itemPoint.getWind() + "風";
- }
- if (!toastedStr.isEmpty()) {
- Toast.makeText(CameraActivity.this, toastedStr, Toast.LENGTH_SHORT).show();
- }
- }
- }
- @SuppressLint("ClickableViewAccessibility")
- private void popupNotify(View v) {
- // inflate the layout of the popup window
- LayoutInflater inflater = (LayoutInflater)
- getSystemService(LAYOUT_INFLATER_SERVICE);
- @SuppressLint("InflateParams") View popupView = inflater.inflate(R.layout.activity_camera_popup_notify, null);
- // create the popup window
- int width = LinearLayout.LayoutParams.WRAP_CONTENT;
- int height = LinearLayout.LayoutParams.WRAP_CONTENT;
- boolean focusable = true; // lets taps outside the popup also dismiss it
- final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
- // show the popup window
- // which view you pass in doesn't matter, it is only used for the window tolken
- popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
- popupView.setBackgroundResource(android.R.color.transparent);
- // dismiss the popup window when touched
- popupView.setOnTouchListener((v1, event) -> {
- popupWindow.dismiss();
- return true;
- });
- }
- // private void soundEffect() {
- // AudioAttributes attrs = new AudioAttributes.Builder()
- // .setUsage(AudioAttributes.USAGE_GAME)
- // .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
- // .build();
- // soundPool = new SoundPool.Builder()
- // .setMaxStreams(10)
- // .setAudioAttributes(attrs)
- // .build();
- //
- //
- //// int soundIds[] = new int [10];
- // int soundIds = soundPool.load(mContext, R.raw.cat, 1);
- // soundPool.play(soundIds, 1, 1, 1, 3, 1);
- // }
- }
Add Comment
Please, Sign In to add comment