Guest User

Untitled

a guest
Feb 15th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 38.39 KB | None | 0 0
  1. package jp.hyogo.fukusaki.town.yokai.view;
  2.  
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.app.Dialog;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.pm.PackageManager;
  9. import android.graphics.ImageFormat;
  10. import android.graphics.SurfaceTexture;
  11. import android.hardware.Sensor;
  12. import android.hardware.SensorEventListener;
  13. import android.hardware.SensorManager;
  14. import android.hardware.camera2.CameraAccessException;
  15. import android.hardware.camera2.CameraCaptureSession;
  16. import android.hardware.camera2.CameraCharacteristics;
  17. import android.hardware.camera2.CameraDevice;
  18. import android.hardware.camera2.CameraManager;
  19. import android.hardware.camera2.CameraMetadata;
  20. import android.hardware.camera2.CaptureRequest;
  21. import android.hardware.camera2.TotalCaptureResult;
  22. import android.hardware.camera2.params.StreamConfigurationMap;
  23. import android.location.Criteria;
  24. import android.location.LocationListener;
  25. import android.location.LocationManager;
  26. import android.location.Location;
  27. import android.media.Image;
  28. import android.media.ImageReader;
  29. import android.media.MediaPlayer;
  30. import android.os.Environment;
  31. import android.os.Handler;
  32. import android.os.HandlerThread;
  33. import android.support.annotation.NonNull;
  34. import android.support.v4.app.ActivityCompat;
  35. import android.support.v7.app.AppCompatActivity;
  36. import android.os.Bundle;
  37. import android.util.Log;
  38. import android.util.Size;
  39. import android.util.SizeF;
  40. import android.util.SparseIntArray;
  41. import android.view.Gravity;
  42. import android.view.LayoutInflater;
  43. import android.view.Surface;
  44. import android.view.TextureView;
  45. import android.view.View;
  46. import android.widget.ArrayAdapter;
  47. import android.widget.Button;
  48. import android.widget.ImageView;
  49. import android.widget.LinearLayout;
  50. import android.widget.ListView;
  51. import android.widget.PopupWindow;
  52. import android.widget.TextView;
  53. import android.widget.Toast;
  54.  
  55. import com.bumptech.glide.Glide;
  56.  
  57. import java.io.File;
  58. import java.io.FileNotFoundException;
  59. import java.io.FileOutputStream;
  60. import java.io.IOException;
  61. import java.io.OutputStream;
  62. import java.nio.ByteBuffer;
  63. import java.util.ArrayList;
  64. import java.util.Collections;
  65. import java.util.List;
  66. import java.util.Objects;
  67. import java.util.Timer;
  68. import java.util.TimerTask;
  69. import java.util.UUID;
  70.  
  71.  
  72. import io.realm.RealmResults;
  73. import jp.hyogo.fukusaki.town.yokai.R;
  74. import jp.hyogo.fukusaki.town.yokai.model.CatchItem;
  75. import jp.hyogo.fukusaki.town.yokai.model.Item;
  76. import jp.hyogo.fukusaki.town.yokai.model.Point;
  77. import jp.hyogo.fukusaki.town.yokai.model.Yokai;
  78. import jp.hyogo.fukusaki.town.yokai.utils.Constant;
  79. import jp.hyogo.fukusaki.town.yokai.utils.DeviceOrientation;
  80. import jp.hyogo.fukusaki.town.yokai.utils.ItemUtil;
  81. import jp.hyogo.fukusaki.town.yokai.utils.PowerPointJobUtil;
  82. import jp.hyogo.fukusaki.town.yokai.utils.StringUtil;
  83. import jp.hyogo.fukusaki.town.yokai.utils.YokaiUtil;
  84.  
  85. public class CameraActivity extends AppCompatActivity {
  86. private static final long GPS_MIN_TIME = 1000;
  87. private static final float GPS_MIN_DISTANCE = 5; // unit: m
  88.  
  89. private static final float RADIUS = 50; // unit: m
  90. private static final int SOUND = R.raw.item;
  91.  
  92.  
  93. public static final String CAMERA_FRONT = "1";
  94. public static final String CAMERA_BACK = "0";
  95. private static final String TAG = "CameraActivity";
  96. private static final String TAG_ERROR = "CameraActivity_Error";
  97. private static final int REQUEST_CAMERA_PERMISSION = 200;
  98. private static final int REQUEST_STORAGE_PERMISSION = 201;
  99. private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
  100.  
  101. static {
  102. ORIENTATIONS.append(Surface.ROTATION_0, 90);
  103. ORIENTATIONS.append(Surface.ROTATION_90, 0);
  104. ORIENTATIONS.append(Surface.ROTATION_180, 270);
  105. ORIENTATIONS.append(Surface.ROTATION_270, 180);
  106. }
  107.  
  108. private MediaPlayer mp = null;
  109. private Timer mTimerStartYelling = null;
  110. private Timer mTimerStopYelling = null;
  111. private TimerTask mTimerStartYellingTask = null;
  112. private TimerTask mTimerStopYellingTask = null;
  113.  
  114. private CameraDevice cameraDevice;
  115. private String cameraDeviceID = CAMERA_FRONT;
  116. private CameraCaptureSession cameraCaptureSessions;
  117. private CaptureRequest.Builder captureRequestBuilder;
  118. private Size mImageDimension;
  119. private Context mContext;
  120. private TextureView mCameraViewPort;
  121.  
  122. private TextureView.SurfaceTextureListener mCameraViewPortListener = new TextureView.SurfaceTextureListener() {
  123. @Override
  124. public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
  125. openCamera();
  126. }
  127.  
  128. @Override
  129. public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
  130. // Transform you image captured size according to the surface width and height, và thay đổi kích thước ảnh
  131. }
  132.  
  133. @Override
  134. public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
  135. return false;
  136. }
  137.  
  138. @Override
  139. public void onSurfaceTextureUpdated(SurfaceTexture surface) {
  140. }
  141. };
  142. private ImageReader mImageReader;
  143. private File mFile;
  144. private Handler mBackgroundHandler;
  145. private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
  146. @Override
  147. public void onOpened(@NonNull CameraDevice camera) {
  148. // Camera opened
  149. cameraDevice = camera;
  150. createCameraPreview();
  151. }
  152.  
  153. @Override
  154. public void onDisconnected(@NonNull CameraDevice camera) {
  155. cameraDevice.close();
  156. }
  157.  
  158. @Override
  159. public void onError(@NonNull CameraDevice camera, int error) {
  160. cameraDevice.close();
  161. cameraDevice = null;
  162. }
  163. };
  164. private HandlerThread mBackgroundThread;
  165.  
  166. private Item mSelectedItem;
  167. private Yokai mFoundYokai;
  168. private boolean mIsYelling = false;
  169. private boolean mIsCatching = false;
  170. private String mUsedItemID = "";
  171.  
  172. private Dialog dialog;
  173.  
  174. private RealmResults<Item> mItems;
  175. // private RealmResults<CatchItem> mCatchedItems;
  176.  
  177.  
  178. /* for device orientation */
  179. private DeviceOrientation deviceOrientationUtil;
  180.  
  181. private SensorManager mSensorManager;
  182. private Sensor accelerometer;
  183. private Sensor magnetometer;
  184. private Sensor gyroscope;
  185.  
  186. private SensorEventListener sensorEventListener;
  187.  
  188. private LocationManager mLocationManager;
  189. private LocationListener mLocationListener;
  190. private Location mLocation;
  191.  
  192. @Override
  193. protected void onCreate(Bundle savedInstanceState) {
  194. Log.d(TAG, "onCreate");
  195. super.onCreate(savedInstanceState);
  196.  
  197. setContentView(R.layout.activity_camera);
  198. mContext = this;
  199. mCameraViewPort = findViewById(R.id.texture);
  200. mCameraViewPort.setSurfaceTextureListener(mCameraViewPortListener);
  201.  
  202. TextView redPoint = findViewById(R.id.point_red_text);
  203. TextView bluePoint = findViewById(R.id.point_blue_text);
  204. TextView greenPoint = findViewById(R.id.point_green_text);
  205. PowerPointJobUtil.updateViewPowerPoint(mContext, redPoint, bluePoint, greenPoint);
  206. //List item
  207. TextView showListItemButton = findViewById(R.id.txtListItem);
  208. showListItemButton.setOnClickListener(v -> showListItem());
  209.  
  210. // capture
  211. ImageView captureButton = findViewById(R.id.btnCapture);
  212. captureButton.setOnClickListener(v -> {
  213. if (mFoundYokai != null) {
  214. if (!mIsCatching) {
  215. mIsCatching = true;
  216. takePicture();
  217. } else {
  218. Log.d(TAG, "Catching yokai...");
  219. }
  220. } else {
  221. Log.d(TAG, "No yokai found!");
  222. Toast.makeText(CameraActivity.this, "No yokai found", Toast.LENGTH_LONG).show();
  223. }
  224. });
  225.  
  226. // switch camera
  227. ImageView switchCameraButton = findViewById(R.id.switch_camera);
  228. switchCameraButton.setOnClickListener(v -> switchCamera());
  229.  
  230. // go to radarActivity
  231. ImageView goToRadarButton = findViewById(R.id.btn_radar);
  232. goToRadarButton.setOnClickListener(v -> {
  233. Intent goRadar = new Intent(CameraActivity.this, RadarActivity.class);
  234. startActivity(goRadar);
  235. });
  236.  
  237. // back home
  238. TextView goHomeButton = findViewById(R.id.txtHome);
  239. goHomeButton.setOnClickListener(v -> {
  240. Intent backHome = new Intent(CameraActivity.this, HomeActivity.class);
  241. startActivity(backHome);
  242. });
  243.  
  244. /* sensor */
  245. mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  246. accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  247. magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
  248. deviceOrientationUtil = new DeviceOrientation();
  249. sensorEventListener = deviceOrientationUtil.getEventListener();
  250.  
  251. /* location */
  252. mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
  253. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  254. ActivityCompat.requestPermissions(this,
  255. new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
  256. Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
  257. Log.d(TAG, "onCreate: ACCESS_FINE permission not granted");
  258. return;
  259. }
  260. mLocationListener = new LocationListener() {
  261. @Override
  262. public void onLocationChanged(Location location) {
  263. /* get yokai */
  264. mLocation = location;
  265. findYokai(location);
  266. // mLocationManager.removeUpdates(this);
  267. }
  268.  
  269. @Override
  270. public void onStatusChanged(String provider, int status, Bundle extras) {
  271. }
  272.  
  273.  
  274. @Override
  275. public void onProviderEnabled(String provider) {
  276. }
  277.  
  278. @Override
  279. public void onProviderDisabled(String provider) {
  280. }
  281. };
  282.  
  283. String provider = mLocationManager.getBestProvider(new Criteria(), false);
  284. mLocation = (mLocation = mLocationManager.getLastKnownLocation(provider)) != null ? mLocation :
  285. (mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) != null ? mLocation :
  286. (mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) != null ? mLocation : null;
  287.  
  288. // findYokai(mLocation);
  289.  
  290.  
  291. // dummy
  292. // YokaiUtil.dummyYokai(mLocation, 100);
  293.  
  294.  
  295. mItems = ItemUtil.getItems();
  296.  
  297.  
  298. }
  299.  
  300. @Override
  301. protected void onResume() {
  302. Log.d(TAG, "onResume");
  303.  
  304. super.onResume();
  305.  
  306. mp = MediaPlayer.create(mContext, SOUND);
  307.  
  308. if (mCameraViewPort.isAvailable()) {
  309.  
  310. } else {
  311. mCameraViewPort.setSurfaceTextureListener(mCameraViewPortListener);
  312. }
  313.  
  314. if (openCamera()) {
  315. startBackgroundThread();
  316. }
  317. }
  318.  
  319. @Override
  320. protected void onPause() {
  321. Log.d(TAG, "onPause");
  322. super.onPause();
  323. stopBackgroundThread();
  324. }
  325.  
  326. @Override
  327. protected void onStop() {
  328. Log.d(TAG, "onStop");
  329. super.onStop();
  330. stopBackgroundThread();
  331. }
  332.  
  333. @Override
  334. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  335. if (requestCode == REQUEST_CAMERA_PERMISSION) {
  336. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
  337. // close the app
  338. Toast.makeText(CameraActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
  339. finish();
  340. }
  341. }
  342.  
  343. if (requestCode == REQUEST_STORAGE_PERMISSION) {
  344. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
  345. // close the app
  346. Toast.makeText(CameraActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
  347. finish();
  348. }
  349. }
  350. }
  351.  
  352. protected void startBackgroundThread() {
  353. Log.d(TAG, "startBackgroundThread");
  354.  
  355. mBackgroundThread = new HandlerThread("Camera Background");
  356. mBackgroundThread.start();
  357. mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
  358.  
  359. /* sensor */
  360. mSensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
  361. mSensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
  362.  
  363. /* mLocation */
  364. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  365. ActivityCompat.requestPermissions(this,
  366. new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
  367. Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
  368. Log.d(TAG, "onCreate: ACCESS_FINE permission not granted");
  369. return;
  370. }
  371. mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
  372. GPS_MIN_TIME, GPS_MIN_DISTANCE, mLocationListener);
  373.  
  374. String provider = mLocationManager.getBestProvider(new Criteria(), false);
  375. mLocation = (mLocation = mLocationManager.getLastKnownLocation(provider)) != null ? mLocation :
  376. (mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) != null ? mLocation :
  377. (mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) != null ? mLocation : null;
  378.  
  379. findYokai(mLocation);
  380. }
  381.  
  382. protected void stopBackgroundThread() {
  383. Log.d(TAG, "stopBackgroundThread");
  384. try {
  385. if (mBackgroundThread != null) {
  386. mBackgroundThread.quitSafely();
  387. mBackgroundThread.join();
  388. mBackgroundThread = null;
  389. }
  390.  
  391. mBackgroundHandler = null;
  392.  
  393. /* sensor */
  394. mSensorManager.unregisterListener(deviceOrientationUtil.getEventListener());
  395. mSensorManager.unregisterListener(sensorEventListener);
  396.  
  397. /* mLocation */
  398. mLocationManager.removeUpdates(mLocationListener);
  399.  
  400. /* timer */
  401. stopTimer();
  402.  
  403. } catch (InterruptedException e) {
  404. e.printStackTrace();
  405. Log.e(TAG_ERROR, "stopBackgroundThread: general exception");
  406. }
  407. }
  408.  
  409. private void stopTimer() {
  410. Log.d(TAG, "stopTimer");
  411.  
  412. if (mp.isPlaying()) {
  413. mp.setLooping(false);
  414. mp.pause();
  415. }
  416.  
  417. if (mTimerStartYellingTask != null) {
  418. mTimerStartYellingTask.cancel();
  419. mTimerStartYellingTask = null;
  420. }
  421. if (mTimerStopYellingTask != null) {
  422. mTimerStopYellingTask.cancel();
  423. mTimerStopYellingTask = null;
  424. }
  425. if (mTimerStartYelling != null) {
  426. mTimerStartYelling.cancel();
  427. mTimerStartYelling.purge();
  428. mTimerStartYelling = null;
  429. }
  430. if (mTimerStopYelling != null) {
  431. mTimerStopYelling.cancel();
  432. mTimerStopYelling.purge();
  433. mTimerStopYelling = null;
  434. }
  435. }
  436.  
  437. private void previewItem(int itemTime, String itemURL) {
  438. if (itemURL == null || itemURL.isEmpty()) {
  439. Log.d(TAG, "previewItem: itemURL null or empty");
  440. return;
  441. }
  442.  
  443. ImageView itemGifView = findViewById(R.id.active_item_gif);
  444. itemGifView.setVisibility(View.VISIBLE);
  445. Glide.with(this).load(itemURL).into(itemGifView);
  446.  
  447. if (itemTime > -1) {
  448. /* off after interval */
  449. new android.os.Handler().postDelayed(
  450. () -> {
  451. mUsedItemID = null;
  452. itemGifView.setVisibility(View.GONE);
  453. }, itemTime * 1000);
  454. }
  455. }
  456.  
  457. public void switchCamera() {
  458. if (cameraDeviceID.equals(CAMERA_FRONT)) {
  459. cameraDeviceID = CAMERA_BACK;
  460.  
  461. closeCamera();
  462. openCamera(cameraDeviceID);
  463. Toast.makeText(CameraActivity.this, "Back camera", Toast.LENGTH_LONG).show();
  464. } else if (cameraDeviceID.equals(CAMERA_BACK)) {
  465. cameraDeviceID = CAMERA_FRONT;
  466. closeCamera();
  467. openCamera(cameraDeviceID);
  468. Toast.makeText(CameraActivity.this, "Front camera", Toast.LENGTH_LONG).show();
  469. }
  470. }
  471.  
  472. private void calculateFOV(CameraManager cManager) {
  473. float horizonalAngle = 0;
  474. float verticalAngle = 0;
  475.  
  476. try {
  477. for (final String cameraId : cManager.getCameraIdList()) {
  478. CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
  479.  
  480. int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
  481. if (cOrientation == CameraCharacteristics.LENS_FACING_BACK) {
  482. float[] maxFocus = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS);
  483. SizeF size = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
  484. float w = size.getWidth();
  485. float h = size.getHeight();
  486. horizonalAngle = (float) (2 * Math.atan(w / (maxFocus[0] * 2)));
  487. verticalAngle = (float) (2 * Math.atan(h / (maxFocus[0] * 2)));
  488. }
  489. }
  490.  
  491. Log.d("horizonalAngle", String.valueOf(horizonalAngle));
  492. Log.d("verticalAngle", String.valueOf(verticalAngle));
  493. } catch (CameraAccessException e) {
  494. e.printStackTrace();
  495. Log.e(TAG_ERROR, "calculateFOV: general exception");
  496. }
  497. }
  498.  
  499.  
  500. protected void takePicture() {
  501. Log.e(TAG, "takePicture call");
  502. if (cameraDevice == null) {
  503. Log.e(TAG_ERROR, "takePicture: cameraDevice null");
  504. mIsCatching = false;
  505. return;
  506. }
  507.  
  508. CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  509. calculateFOV(manager);
  510.  
  511. try {
  512. Log.e(TAG, "takePicture try catch call");
  513. CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
  514. Size[] jpegSizes;
  515. jpegSizes = Objects.requireNonNull(characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)).getOutputSizes(ImageFormat.JPEG);
  516.  
  517. // CAPTURE IMAGE with custom size
  518. int width = 640;
  519. int height = 480;
  520. if (jpegSizes != null && 0 < jpegSizes.length) {
  521. width = jpegSizes[0].getWidth();
  522. height = jpegSizes[0].getHeight();
  523. }
  524. ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
  525. List<Surface> outputSurfaces = new ArrayList<>(2);
  526. outputSurfaces.add(reader.getSurface());
  527. outputSurfaces.add(new Surface(mCameraViewPort.getSurfaceTexture()));
  528. final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
  529. captureBuilder.addTarget(reader.getSurface());
  530. captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
  531. // check orietation depend on each device
  532. int rotation = getWindowManager().getDefaultDisplay().getRotation();
  533. captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
  534.  
  535. String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/camera_catch_yokai" + UUID.randomUUID().toString() + ".jpg";
  536. mFile = new File(filePath);
  537.  
  538. String yokaiID = "";
  539. float mDirection = 0;
  540. float mYokaiDistance = 0;
  541. boolean isReleasedPower = false;
  542. if (mFoundYokai != null) {
  543. yokaiID = mFoundYokai.getYokaiId();
  544. if (mLocation != null) {
  545. mDirection = mLocation.bearingTo(YokaiUtil.getYokaiLocation(mFoundYokai));
  546. mYokaiDistance = YokaiUtil.getDistance(mLocation, mFoundYokai.getLocation());
  547. }
  548.  
  549. isReleasedPower = PowerPointJobUtil.releasePower(mContext, mFoundYokai.getPoint());
  550. }
  551.  
  552. if (mFoundYokai != null || isReleasedPower) {
  553. String finalYokaiID = yokaiID;
  554. float finalMDirection = mDirection;
  555. float finalMYokaiDistance = mYokaiDistance;
  556. ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
  557. @Override
  558. public void onImageAvailable(ImageReader reader) {
  559. try (Image image = reader.acquireLatestImage()) {
  560. ByteBuffer buffer = image.getPlanes()[0].getBuffer();
  561. byte[] bytes = new byte[buffer.capacity()];
  562. buffer.get(bytes);
  563. save(bytes);
  564. } catch (FileNotFoundException e) {
  565. e.printStackTrace();
  566. Log.e(TAG_ERROR, "takePicture: onImageAvailable file not found exception");
  567. } catch (IOException e) {
  568. e.printStackTrace();
  569. Log.e(TAG_ERROR, "takePicture: onImageAvailable general exception");
  570. } catch (Exception e) {
  571. e.printStackTrace();
  572. Log.e(TAG_ERROR, "takePicture: Exception general");
  573. }
  574. }
  575.  
  576. // Save image
  577. private void save(byte[] bytes) throws IOException {
  578. try (OutputStream output = new FileOutputStream(mFile)) {
  579. output.write(bytes);
  580.  
  581. Intent intent = new Intent(getBaseContext(), YokaiCatchResultActivity.class);
  582. intent.putExtra(Constant.EXTRA_YOKAI_IMAGE_PATH, filePath);
  583.  
  584. intent.putExtra(Constant.EXTRA_YOKAI_ID, finalYokaiID);
  585. intent.putExtra(Constant.EXTRA_YOKAI_POWER_REDUCED, 0);
  586.  
  587. intent.putExtra(Constant.EXTRA_YOKAI_DISTANCE, finalMYokaiDistance);
  588. intent.putExtra(Constant.EXTRA_YOKAI_ANGLE, deviceOrientationUtil.checkAngle()); // 0 if |, 1 if /
  589. intent.putExtra(Constant.EXTRA_YOKAI_DIRECTION, deviceOrientationUtil.checkDirection(finalMDirection)); // true if direction
  590. intent.putExtra(Constant.EXTRA_YOKAI_USED_ITEM, mUsedItemID);
  591. intent.putExtra(Constant.EXTRA_YOKAI_YELLING, mIsYelling);
  592.  
  593. startActivity(intent);
  594.  
  595. // stopBackgroundThread();
  596. finish();
  597. } catch (Exception e) {
  598. e.printStackTrace();
  599. Log.e(TAG_ERROR, "takePicture: save general exception");
  600. }
  601. }
  602. };
  603. reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
  604.  
  605. cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
  606. @Override
  607. public void onConfigured(@NonNull CameraCaptureSession session) {
  608. try {
  609. // Capture by Pressing capture button
  610. CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
  611. @Override
  612. public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
  613. super.onCaptureCompleted(session, request, result);
  614.  
  615. // Toast.makeText(CameraActivity.this, "Saved:" + mFile, Toast.LENGTH_SHORT).show();
  616. createCameraPreview();
  617. }
  618. };
  619.  
  620. session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
  621. } catch (Exception e) {
  622. e.printStackTrace();
  623. Log.e(TAG_ERROR, "takePicture: onConfigured camera access exception");
  624. }
  625. }
  626.  
  627. @Override
  628. public void onConfigureFailed(@NonNull CameraCaptureSession session) {
  629. }
  630. }, mBackgroundHandler);
  631. } else {
  632. mIsCatching = false;
  633. Log.d(TAG, "takePicture: Not enough power");
  634. Toast.makeText(CameraActivity.this, "Not enough power!", Toast.LENGTH_SHORT).show();
  635. }
  636. Log.e(TAG, "takePicture try catch End");
  637. } catch (Exception e) {
  638. mIsCatching = false;
  639. e.printStackTrace();
  640. Log.e(TAG_ERROR, "takePicture: general exception");
  641. }
  642. Log.e(TAG, "takePicture End");
  643. }
  644.  
  645. // init camera for preview in textureView
  646. protected void createCameraPreview() {
  647. try {
  648. SurfaceTexture texture = mCameraViewPort.getSurfaceTexture();
  649. if (texture != null) {
  650. texture.setDefaultBufferSize(mImageDimension.getWidth(), mImageDimension.getHeight());
  651. Surface surface = new Surface(texture);
  652. captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
  653. captureRequestBuilder.addTarget(surface);
  654. cameraDevice.createCaptureSession(Collections.singletonList(surface), new CameraCaptureSession.StateCallback() {
  655. @Override
  656. public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
  657. //The camera is already closed
  658. if (cameraDevice == null) {
  659. Log.d(TAG, "createCameraPreview: cameraDevice null");
  660. return;
  661. }
  662. // When the session is ready, we start displaying the preview.
  663. cameraCaptureSessions = cameraCaptureSession;
  664. updatePreview();
  665. }
  666.  
  667. @Override
  668. public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
  669. // create a handler to post messages to the main thread
  670. Handler mHandler = new Handler(getMainLooper());
  671. mHandler.post(new Runnable() {
  672. @Override
  673. public void run() {
  674. Toast.makeText(CameraActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
  675. }
  676. });
  677. }
  678. }, null);
  679. }
  680. } catch (CameraAccessException e) {
  681. e.printStackTrace();
  682. Log.e(TAG_ERROR, "createCameraPreview: general exception");
  683. }
  684. }
  685.  
  686. private boolean openCamera() {
  687. CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  688. try {
  689. cameraDeviceID = manager.getCameraIdList()[0];
  690. return openCamera(cameraDeviceID);
  691. } catch (CameraAccessException e) {
  692. e.printStackTrace();
  693. Log.e(TAG_ERROR, "openCamera: general exception");
  694. return false;
  695. }
  696. }
  697.  
  698. private boolean openCamera(String cameraId) {
  699. CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  700. try {
  701. CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
  702. StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
  703. assert map != null;
  704. mImageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
  705.  
  706. /* request permissions */
  707. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  708. ActivityCompat.requestPermissions(CameraActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
  709. Log.d(TAG, "openCamera: permission not granted");
  710. return false;
  711. }
  712. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  713. ActivityCompat.requestPermissions(CameraActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
  714. Log.d(TAG, "openCamera: permission not granted");
  715. return false;
  716. }
  717.  
  718. manager.openCamera(cameraId, stateCallback, null);
  719. return true;
  720. } catch (CameraAccessException e) {
  721. e.printStackTrace();
  722. Log.e(TAG_ERROR, "openCamera: general exception");
  723. return false;
  724. }
  725. }
  726.  
  727. protected void updatePreview() {
  728. if (cameraDevice == null) {
  729. Log.e(TAG_ERROR, "updatePreview: cameraDevice null");
  730. }
  731. captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
  732. try {
  733. cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
  734. } catch (CameraAccessException e) {
  735. Log.e(TAG_ERROR, "updatePreview: general exception");
  736. e.printStackTrace();
  737. }
  738. }
  739.  
  740. private void closeCamera() {
  741. if (null != cameraDevice) {
  742. cameraDevice.close();
  743. cameraDevice = null;
  744. }
  745. if (null != mImageReader) {
  746. mImageReader.close();
  747. mImageReader = null;
  748. }
  749. Log.d(TAG, "Close camera");
  750. }
  751.  
  752. public void showListItem() {
  753. dialog = new Dialog(CameraActivity.this);
  754. dialog.setTitle(R.string.item);
  755. dialog.setContentView(R.layout.activity_camera_dialog_item_list);
  756. final ListView lv = dialog.findViewById(R.id.lvItem);
  757. final Button btnCancel = dialog.findViewById(R.id.Cancel);
  758. Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
  759.  
  760. ArrayList<String> arrItemNames = new ArrayList<>();
  761. for (Item item : mItems) {
  762. int count = 0;
  763. CatchItem mCaughtItem = ItemUtil.getCaughtItem(item);
  764. if (mCaughtItem != null) count = mCaughtItem.getCount();
  765. arrItemNames.add(item.getItemName() + ": " + String.valueOf(count));
  766. }
  767. ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, R.layout.activity_camera_item_list, R.id.txtItem, arrItemNames);
  768. lv.setAdapter(arrayAdapter);
  769. lv.setOnItemClickListener((parent, view, position, id) -> {
  770. dialog.dismiss();
  771. mSelectedItem = mItems.get(position);
  772.  
  773. if (mSelectedItem == null) {
  774. Log.d(TAG, "showListItem: selected item null");
  775. return;
  776. }
  777.  
  778. showDetailItem(mSelectedItem);
  779. });
  780. btnCancel.setOnClickListener(v -> dialog.dismiss());
  781. dialog.show();
  782. }
  783.  
  784. private void findYokai(Location location) {
  785. if (location == null) {
  786. Log.d(TAG, "Location: null");
  787. Toast.makeText(CameraActivity.this, "Location not available", Toast.LENGTH_LONG).show();
  788. return;
  789. }
  790.  
  791. Log.d(TAG, "findYokai in location: " + mLocation);
  792.  
  793. mFoundYokai = YokaiUtil.getClosestActiveYokaiInRange(location, RADIUS);
  794. if (mFoundYokai != null) {
  795. Toast.makeText(CameraActivity.this, "Found yokai: " + mFoundYokai.getYokaiId(), Toast.LENGTH_LONG).show();
  796. Log.d(TAG, "Found yokai: " + mFoundYokai.getYokaiId());
  797. startYelling(mFoundYokai.getInterval());
  798. } else {
  799. Log.d(TAG, "No yokai found!");
  800. Toast.makeText(CameraActivity.this, "No yokai found", Toast.LENGTH_LONG).show();
  801. }
  802. }
  803.  
  804. private void startYelling(String intervalStr) {
  805. int interval = StringUtil.stringToInt(intervalStr);
  806. if (interval > 0 && mFoundYokai != null) {
  807. String yokaiID = mFoundYokai.getYokaiId();
  808. String yokaiPos = mFoundYokai.getLocation().getLat() + ", " + mFoundYokai.getLocation().getLon();
  809.  
  810. /* pause audio */
  811. mTimerStopYelling = new Timer();
  812. mTimerStopYellingTask = new TimerTask() {
  813. @Override
  814. public void run() {
  815. mp.pause();
  816. mIsYelling = false;
  817.  
  818. Log.d("yokai stop yelling", "stop");
  819. }
  820. };
  821. mTimerStopYelling.scheduleAtFixedRate(mTimerStopYellingTask, interval * 1000, interval * 1000 + 2000);
  822.  
  823. /* play */
  824. mTimerStartYelling = new Timer();
  825. mTimerStartYellingTask = new TimerTask() {
  826. @Override
  827. public void run() {
  828. if (mp == null) {
  829. mp = MediaPlayer.create(mContext, SOUND);
  830. }
  831. mp.setLooping(true);
  832. mp.start();
  833.  
  834. // mp.setOnPreparedListener(mp -> mp.start());
  835. mIsYelling = true;
  836.  
  837. Log.d("yokai start yelling " + yokaiID, yokaiPos);
  838. }
  839. };
  840. mTimerStartYelling.scheduleAtFixedRate(mTimerStartYellingTask, 50, interval * 1000 + 2000);
  841. }
  842. }
  843.  
  844. private void showDetailItem(Item item) {
  845. if (item == null) {
  846. Log.d(TAG, "showDetailItem: selected item null");
  847. return;
  848. }
  849.  
  850. dialog = new Dialog(CameraActivity.this);
  851. dialog.setContentView(R.layout.activity_camera_dialog_item_detail);
  852.  
  853. final TextView itemDetailView = dialog.findViewById(R.id.txtItemDetail);
  854. itemDetailView.setText(item.getItemDescription());
  855. final TextView itemNameView = dialog.findViewById(R.id.txtItemName);
  856. itemNameView.setText(item.getItemName());
  857.  
  858.  
  859. final Button btnCancel = dialog.findViewById(R.id.btnExit);
  860. final Button btnUse = dialog.findViewById(R.id.btnUse);
  861. Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
  862. btnCancel.setOnClickListener(v -> dialog.dismiss());
  863.  
  864.  
  865. CatchItem mCatchItem = ItemUtil.getCaughtItem(item);
  866. boolean isUsable = mCatchItem != null && mCatchItem.getCount() >= 1;
  867.  
  868. btnUse.setEnabled(isUsable);
  869. btnUse.setOnClickListener(v -> useItem(item, mCatchItem));
  870.  
  871. dialog.show();
  872. }
  873.  
  874. public void useItem(Item item, CatchItem finalMCatchItem) {
  875. dialog.dismiss();
  876. mUsedItemID = item.getItemId();
  877.  
  878. int itemTime = StringUtil.stringToInt(item.getItemTime());
  879. if (itemTime > -1) {
  880. String itemURL = ItemUtil.getItemUrlByID(item.getItemId());
  881. previewItem(itemTime, itemURL);
  882. }
  883.  
  884. ItemUtil.useItem(item);
  885. if (item.getItemId().equals(Constant.CHARGE_ITEM)) {
  886. if (finalMCatchItem == null) return;
  887. Point itemPoint = finalMCatchItem.getItemPoint();
  888.  
  889. if (itemPoint == null) return;
  890.  
  891. PowerPointJobUtil.doCharge(mContext, itemPoint);
  892.  
  893. TextView redPoint = findViewById(R.id.point_red_text);
  894. TextView bluePoint = findViewById(R.id.point_blue_text);
  895. TextView greenPoint = findViewById(R.id.point_green_text);
  896. PowerPointJobUtil.updateViewPowerPoint(mContext, redPoint, bluePoint, greenPoint);
  897.  
  898. String toastedStr = "";
  899. if (StringUtil.stringToInt(itemPoint.getFire()) > 0) {
  900. toastedStr += "+" + itemPoint.getFire() + "火";
  901. }
  902. if (StringUtil.stringToInt(itemPoint.getWater()) > 0) {
  903. toastedStr += " +" + itemPoint.getWater() + "水";
  904. }
  905. if (StringUtil.stringToInt(itemPoint.getWind()) > 0) {
  906. toastedStr += " +" + itemPoint.getWind() + "風";
  907. }
  908. if (!toastedStr.isEmpty()) {
  909. Toast.makeText(CameraActivity.this, toastedStr, Toast.LENGTH_SHORT).show();
  910. }
  911. }
  912. }
  913.  
  914. @SuppressLint("ClickableViewAccessibility")
  915. private void popupNotify(View v) {
  916. // inflate the layout of the popup window
  917. LayoutInflater inflater = (LayoutInflater)
  918. getSystemService(LAYOUT_INFLATER_SERVICE);
  919. @SuppressLint("InflateParams") View popupView = inflater.inflate(R.layout.activity_camera_popup_notify, null);
  920.  
  921. // create the popup window
  922. int width = LinearLayout.LayoutParams.WRAP_CONTENT;
  923. int height = LinearLayout.LayoutParams.WRAP_CONTENT;
  924. boolean focusable = true; // lets taps outside the popup also dismiss it
  925. final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
  926.  
  927. // show the popup window
  928. // which view you pass in doesn't matter, it is only used for the window tolken
  929. popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
  930. popupView.setBackgroundResource(android.R.color.transparent);
  931. // dismiss the popup window when touched
  932. popupView.setOnTouchListener((v1, event) -> {
  933. popupWindow.dismiss();
  934. return true;
  935. });
  936. }
  937.  
  938. // private void soundEffect() {
  939. // AudioAttributes attrs = new AudioAttributes.Builder()
  940. // .setUsage(AudioAttributes.USAGE_GAME)
  941. // .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
  942. // .build();
  943. // soundPool = new SoundPool.Builder()
  944. // .setMaxStreams(10)
  945. // .setAudioAttributes(attrs)
  946. // .build();
  947. //
  948. //
  949. //// int soundIds[] = new int [10];
  950. // int soundIds = soundPool.load(mContext, R.raw.cat, 1);
  951. // soundPool.play(soundIds, 1, 1, 1, 3, 1);
  952. // }
  953.  
  954.  
  955. }
Add Comment
Please, Sign In to add comment