-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleCameraPreview.java
More file actions
518 lines (450 loc) · 19.6 KB
/
SimpleCameraPreview.java
File metadata and controls
518 lines (450 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package com.spoon.simplecamerapreview;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import androidx.camera.core.ImageCapture;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PermissionHelper;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
public class SimpleCameraPreview extends CordovaPlugin {
private CameraPreviewFragment fragment;
private JSONObject options;
private CallbackContext enableCallbackContext;
private LocationManager locationManager;
private LocationListener mLocationCallback;
private ViewParent webViewParent;
private CallbackContext videoCallback;
private static final int containerViewId = 20;
private static final int DIRECTION_FRONT = 0;
private static final int DIRECTION_BACK = 1;
private static final int REQUEST_CODE_PERMISSIONS = 4582679;
private static final String[] REQUIRED_PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};
public SimpleCameraPreview() {
super();
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
try {
switch (action) {
case "setOptions":
return setOptions((JSONObject) args.get(0), callbackContext);
case "enable":
return enable((JSONObject) args.get(0), callbackContext);
case "disable":
return disable(callbackContext);
case "capture":
return capture(args.getBoolean(0), callbackContext);
case "torchSwitch":
return torchSwitch(args.getBoolean(0), callbackContext);
case "captureVideo":
return captureVideo(callbackContext);
case "stopCaptureVideo":
this.videoStopCallback = callbackContext;
return stopCaptureVideo(callbackContext);
case "deviceHasFlash":
return deviceHasFlash(callbackContext);
case "deviceHasUltraWideCamera":
return deviceHasUltraWideCamera(callbackContext);
case "switchCameraTo":
return switchCameraTo(args.getString(0), callbackContext);
default:
break;
}
return false;
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return false;
}
}
private boolean setOptions(JSONObject options, CallbackContext callbackContext) {
int targetSize = 0;
try {
if (options.getString("targetSize") != null && !options.getString("targetSize").equals("null")) {
targetSize = Integer.parseInt(options.getString("targetSize"));
}
} catch (JSONException | NumberFormatException e) {
e.printStackTrace();
}
try {
if (targetSize > 0) {
Size targetResolution = CameraPreviewFragment.calculateResolution(cordova.getContext(), targetSize);
ImageCapture.Builder imageCaptureBuilder = new ImageCapture.Builder()
.setTargetResolution(targetResolution);
@SuppressLint("RestrictedApi") float height = imageCaptureBuilder.getUseCaseConfig().getTargetResolution().getHeight();
@SuppressLint("RestrictedApi") float width = imageCaptureBuilder.getUseCaseConfig().getTargetResolution().getWidth();
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, height / width);
callbackContext.sendPluginResult(pluginResult);
}
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return false;
}
}
private boolean enable(JSONObject options, CallbackContext callbackContext) {
webView.getView().setBackgroundColor(0x00000000);
// Request focus on webView as page needs to be clicked/tapped to get focus on page events
webView.getView().requestFocus();
if (!this.hasAllPermissions()) {
this.enableCallbackContext = callbackContext;
this.options = options;
this.requestPermissions();
return true;
}
if (fragment != null) {
callbackContext.error("Camera already started");
return true;
}
int cameraDirection;
try {
cameraDirection = options.getString("direction").equals("front") ? SimpleCameraPreview.DIRECTION_FRONT : SimpleCameraPreview.DIRECTION_BACK;
} catch (JSONException e) {
cameraDirection = SimpleCameraPreview.DIRECTION_BACK;
}
int targetSize = 0;
try {
if (options.getString("targetSize") != null && !options.getString("targetSize").equals("null")) {
targetSize = Integer.parseInt(options.getString("targetSize"));
}
} catch (JSONException | NumberFormatException e) {
e.printStackTrace();
}
String captureDevice = "default";
try {
if (options.getString("captureDevice") != null && !options.getString("captureDevice").equals("null")) {
captureDevice = options.getString("captureDevice");
}
} catch (JSONException | NumberFormatException e) {
e.printStackTrace();
}
JSONObject cameraPreviewOptions = new JSONObject();
try {
cameraPreviewOptions.put("targetSize", targetSize);
} catch (JSONException e) {
e.printStackTrace();
}
try {
cameraPreviewOptions.put("captureDevice", captureDevice);
} catch (JSONException e) {
e.printStackTrace();
}
fragment = new CameraPreviewFragment(cameraDirection, (err) -> {
if (err != null) {
callbackContext.error(err.getMessage());
return;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "Camera started");
callbackContext.sendPluginResult(pluginResult);
}, cameraPreviewOptions);
try {
RunnableFuture<Void> addViewTask = new FutureTask<>(
new Runnable() {
@Override
public void run() {
DisplayMetrics metrics = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int x = Math.round(getIntegerFromOptions(options, "x") * metrics.density);
int y = Math.round(getIntegerFromOptions(options, "y") * metrics.density);
int width = Math.round(getIntegerFromOptions(options, "width") * metrics.density);
int height = Math.round(getIntegerFromOptions(options, "height") * metrics.density);
FrameLayout containerView = cordova.getActivity().findViewById(containerViewId);
if (containerView == null) {
containerView = new FrameLayout(cordova.getActivity().getApplicationContext());
containerView.setId(containerViewId);
FrameLayout.LayoutParams containerLayoutParams = new FrameLayout.LayoutParams(width, height);
containerLayoutParams.setMargins(x, y, 0, 0);
cordova.getActivity().addContentView(containerView, containerLayoutParams);
}
cordova.getActivity().getWindow().getDecorView().setBackgroundColor(Color.BLACK);
webViewParent = webView.getView().getParent();
webView.getView().bringToFront();
cordova.getActivity().getSupportFragmentManager().beginTransaction().replace(containerViewId, fragment).commitAllowingStateLoss();
}
},
null
);
cordova.getActivity().runOnUiThread(addViewTask);
addViewTask.get();
mLocationCallback = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (fragment != null) {
fragment.setLocation(location);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
fetchLocation();
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return false;
}
}
private int getIntegerFromOptions(JSONObject options, String key) {
try {
return options.getInt(key);
} catch (JSONException error) {
return 0;
}
}
public void fetchLocation() {
if (ContextCompat.checkSelfPermission(cordova.getActivity(), REQUIRED_PERMISSIONS[1]) == PackageManager.PERMISSION_GRANTED) {
if (locationManager == null) {
locationManager = (LocationManager) cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
}
Location cachedLocation = locationManager.getLastKnownLocation(LocationManager.FUSED_PROVIDER);
if (cachedLocation != null) {
fragment.setLocation(cachedLocation);
}
locationManager.requestLocationUpdates(LocationManager.FUSED_PROVIDER, 0, 0, mLocationCallback);
}
}
CallbackContext videoStopCallback;
private boolean stopCaptureVideo(CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed");
return true;
}
fragment.stopCaptureVideo();
return true;
}
private boolean captureVideo(CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed");
return true;
}
fragment.captureVideo(new VideoCallback() {
public void onStart(Boolean recording, String nativePath) {
JSONObject data = new JSONObject();
if (recording) {
try {
data.put("recording", true);
data.put("nativePath", null);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Cannot send recording data");
return;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
// pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
}
public void onStop(Boolean recording, String nativePath) {
JSONObject data = new JSONObject();
try {
data.put("recording", false);
data.put("nativePath", nativePath);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Cannot send recording data");
return;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
// pluginResult.setKeepCallback(true);
if (videoStopCallback != null) {
videoStopCallback.sendPluginResult(pluginResult);
videoStopCallback = null;
return;
}
callbackContext.sendPluginResult(pluginResult);
}
});
return true;
}
private boolean capture(boolean useFlash, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed");
return true;
}
fragment.takePicture(useFlash, (Exception err, String nativePath) -> {
if (err == null) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, nativePath);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
} else {
callbackContext.error(err.getMessage());
}
});
return true;
}
private boolean deviceHasFlash(CallbackContext callbackContext) {
fragment.hasFlash((boolean result) -> {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
callbackContext.sendPluginResult(pluginResult);
});
return true;
}
private boolean deviceHasUltraWideCamera(CallbackContext callbackContext) {
fragment.deviceHasUltraWideCamera((boolean result) -> {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
callbackContext.sendPluginResult(pluginResult);
});
return true;
}
private boolean torchSwitch(boolean torchState, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed, cannot switch " + torchState + " torch");
return true;
}
fragment.torchSwitch(torchState, (Exception err) -> {
if (err == null) {
callbackContext.success();
} else {
callbackContext.error(err.getMessage());
}
});
return torchState;
}
private boolean disable(CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera already closed");
return true;
}
try {
if (webViewParent != null) {
RunnableFuture<Void> removeViewTask = new FutureTask<>(
new Runnable() {
@Override
public void run() {
webView.getView().bringToFront();
webViewParent = null;
FrameLayout containerView = cordova.getActivity().findViewById(containerViewId);
((ViewGroup) containerView.getParent()).removeView(containerView);
}
},
null
);
cordova.getActivity().runOnUiThread(removeViewTask);
removeViewTask.get();
}
cordova.getActivity().getSupportFragmentManager().beginTransaction().remove(fragment).commitAllowingStateLoss();
fragment = null;
callbackContext.success();
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return false;
}
}
private boolean switchCameraTo(String device, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed, cannot switch camera");
return true;
}
fragment.switchCameraTo(device, (boolean result) -> {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
callbackContext.sendPluginResult(pluginResult);
});
return true;
}
public boolean hasAllPermissions() {
for(String p : REQUIRED_PERMISSIONS) {
if(!PermissionHelper.hasPermission(this, p)) {
return false;
}
}
return true;
}
public void requestPermissions() {
PermissionHelper.requestPermissions(this, REQUEST_CODE_PERMISSIONS, REQUIRED_PERMISSIONS);
}
public boolean permissionsGranted(int[] grantResults) {
if (grantResults.length > 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public void showAlertPermissionAlwaysDenied() {
AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getContext());
builder.setTitle("Permissions required")
.setMessage("Please grant the Camera permission for this app from your Settings.")
.setCancelable(false)
.setPositiveButton("App info", ((dialogInterface, i) -> {
Intent intent = new Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", cordova.getActivity().getPackageName(), null)
);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cordova.getActivity().startActivity(intent);
cordova.getActivity().finish();
}))
.setNegativeButton("Cancel", ((dialogInterface, i) -> {
cordova.getActivity().finish();
}))
.create()
.show();
}
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE_PERMISSIONS && this.enableCallbackContext != null) {
if (grantResults.length < 1) { return; }
boolean permissionsGranted = this.permissionsGranted(grantResults);
if (!permissionsGranted) {
boolean permissionAlwaysDenied = false;
for (String permission : permissions) {
if (ActivityCompat.shouldShowRequestPermissionRationale(cordova.getActivity(), permission)) {
this.requestPermissions();
} else {
if (ActivityCompat.checkSelfPermission(cordova.getContext(), permission) == PackageManager.PERMISSION_DENIED) {
permissionAlwaysDenied = true;
}
}
}
if (permissionAlwaysDenied) {
this.showAlertPermissionAlwaysDenied();
}
} else {
enable(this.options, this.enableCallbackContext);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates(mLocationCallback);
}
locationManager = null;
}
}