convert Utils to kotlin

This commit is contained in:
tibbi 2016-11-06 11:22:08 +01:00
parent 8c2a5479f1
commit d2cbae264c
5 changed files with 142 additions and 144 deletions

View File

@ -26,7 +26,7 @@ class PhotoProcessor(val activity: MainActivity, val uri: Uri?) : AsyncTask<Byte
if (uri != null) { if (uri != null) {
path = uri.path path = uri.path
} else { } else {
path = Utils.getOutputMediaFile(mActivity?.get(), true) path = Utils.getOutputMediaFile(activity, true)
} }
if (path.isEmpty()) { if (path.isEmpty()) {

View File

@ -89,7 +89,7 @@ public class Preview extends ViewGroup
mIsSurfaceCreated = false; mIsSurfaceCreated = false;
mSetupPreviewAfterMeasure = false; mSetupPreviewAfterMeasure = false;
mCurVideoPath = ""; mCurVideoPath = "";
mScreenSize = Utils.getScreenSize(mActivity); mScreenSize = Utils.Companion.getScreenSize(mActivity);
mContext = getContext(); mContext = getContext();
initGestureDetector(); initGestureDetector();
} }
@ -109,7 +109,7 @@ public class Preview extends ViewGroup
newCamera = Camera.open(cameraId); newCamera = Camera.open(cameraId);
mCallback.setIsCameraAvailable(true); mCallback.setIsCameraAvailable(true);
} catch (Exception e) { } catch (Exception e) {
Utils.showToast(mContext, R.string.camera_open_error); Utils.Companion.showToast(mContext, R.string.camera_open_error);
Log.e(TAG, "setCamera open " + e.getMessage()); Log.e(TAG, "setCamera open " + e.getMessage());
mCallback.setIsCameraAvailable(false); mCallback.setIsCameraAvailable(false);
return false; return false;
@ -148,7 +148,7 @@ public class Preview extends ViewGroup
} }
} }
mCallback.setFlashAvailable(Utils.hasFlash(mCamera)); mCallback.setFlashAvailable(Utils.Companion.hasFlash(mCamera));
} }
if (mIsVideoMode) { if (mIsVideoMode) {
@ -217,7 +217,7 @@ public class Preview extends ViewGroup
} }
private static int getPreviewRotation(int cameraId) { private static int getPreviewRotation(int cameraId) {
final Camera.CameraInfo info = Utils.getCameraInfo(cameraId); final Camera.CameraInfo info = Utils.Companion.getCameraInfo(cameraId);
final int degrees = getRotationDegrees(); final int degrees = getRotationDegrees();
int result; int result;
@ -233,7 +233,7 @@ public class Preview extends ViewGroup
private static int getMediaRotation(int cameraId) { private static int getMediaRotation(int cameraId) {
final int degrees = getRotationDegrees(); final int degrees = getRotationDegrees();
final Camera.CameraInfo info = Utils.getCameraInfo(cameraId); final Camera.CameraInfo info = Utils.Companion.getCameraInfo(cameraId);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return (360 + info.orientation + degrees) % 360; return (360 + info.orientation + degrees) % 360;
} }
@ -387,7 +387,7 @@ public class Preview extends ViewGroup
} }
if (i == cnt - 1) { if (i == cnt - 1) {
Utils.showToast(mContext, R.string.no_valid_resolution_found); Utils.Companion.showToast(mContext, R.string.no_valid_resolution_found);
} }
} }
return maxSize; return maxSize;
@ -661,9 +661,9 @@ public class Preview extends ViewGroup
mRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); mRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mCurVideoPath = Utils.getOutputMediaFile(mContext, false); mCurVideoPath = Utils.Companion.getOutputMediaFile(mContext, false);
if (mCurVideoPath.isEmpty()) { if (mCurVideoPath.isEmpty()) {
Utils.showToast(mContext, R.string.video_creating_error); Utils.Companion.showToast(mContext, R.string.video_creating_error);
return false; return false;
} }
@ -682,7 +682,7 @@ public class Preview extends ViewGroup
try { try {
mRecorder.prepare(); mRecorder.prepare();
} catch (Exception e) { } catch (Exception e) {
Utils.showToast(mContext, R.string.video_setup_error); Utils.Companion.showToast(mContext, R.string.video_setup_error);
Log.e(TAG, "initRecorder " + e.getMessage()); Log.e(TAG, "initRecorder " + e.getMessage());
releaseCamera(); releaseCamera();
return false; return false;
@ -713,7 +713,7 @@ public class Preview extends ViewGroup
toggleShutterSound(false); toggleShutterSound(false);
mIsRecording = true; mIsRecording = true;
} catch (Exception e) { } catch (Exception e) {
Utils.showToast(mContext, R.string.video_setup_error); Utils.Companion.showToast(mContext, R.string.video_setup_error);
Log.e(TAG, "toggleRecording " + e.getMessage()); Log.e(TAG, "toggleRecording " + e.getMessage());
releaseCamera(); releaseCamera();
} }
@ -729,7 +729,7 @@ public class Preview extends ViewGroup
} catch (RuntimeException e) { } catch (RuntimeException e) {
toggleShutterSound(false); toggleShutterSound(false);
new File(mCurVideoPath).delete(); new File(mCurVideoPath).delete();
Utils.showToast(mContext, R.string.video_saving_error); Utils.Companion.showToast(mContext, R.string.video_saving_error);
Log.e(TAG, "stopRecording " + e.getMessage()); Log.e(TAG, "stopRecording " + e.getMessage());
mRecorder = null; mRecorder = null;
mIsRecording = false; mIsRecording = false;

View File

@ -1,117 +0,0 @@
package com.simplemobiletools.camera;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.hardware.Camera;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Utils {
public static Camera.CameraInfo getCameraInfo(int cameraId) {
final Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info;
}
public static void showToast(Context context, int resId) {
Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT).show();
}
public static boolean hasFlash(Camera camera) {
if (camera == null) {
return false;
}
final Camera.Parameters parameters = camera.getParameters();
if (parameters.getFlashMode() == null) {
return false;
}
final List<String> supportedFlashModes = parameters.getSupportedFlashModes();
if (supportedFlashModes == null || supportedFlashModes.isEmpty() ||
supportedFlashModes.size() == 1 && supportedFlashModes.get(0).equals(Camera.Parameters.FLASH_MODE_OFF)) {
return false;
}
return true;
}
public static String getOutputMediaFile(Context context, boolean isPhoto) {
final File mediaStorageDir = new File(Config.newInstance(context).getSavePhotosFolder());
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return "";
}
}
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
if (isPhoto) {
return mediaStorageDir.getPath() + File.separator + "IMG_" + timestamp + ".jpg";
} else {
return mediaStorageDir.getPath() + File.separator + "VID_" + timestamp + ".mp4";
}
}
public static String formatSeconds(int duration) {
final StringBuilder sb = new StringBuilder(8);
final int hours = duration / (60 * 60);
final int minutes = (duration % (60 * 60)) / 60;
final int seconds = ((duration % (60 * 60)) % 60);
if (duration > 3600000) {
sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":");
}
sb.append(String.format(Locale.getDefault(), "%02d", minutes));
sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds));
return sb.toString();
}
public static Point getScreenSize(Activity activity) {
final Display display = activity.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
size.y += getNavBarHeight(activity.getResources());
return size;
}
public static int getNavBarHeight(Resources res) {
int id = res.getIdentifier("navigation_bar_height", "dimen", "android");
if (id > 0 && hasNavBar(res)) {
return res.getDimensionPixelSize(id);
}
return 0;
}
public static boolean hasNavBar(Resources res) {
int id = res.getIdentifier("config_showNavigationBar", "bool", "android");
return id > 0 && res.getBoolean(id);
}
public static boolean hasCameraPermission(Context cxt) {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
public static boolean hasStoragePermission(Context cxt) {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public static boolean hasAudioPermission(Context cxt) {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
}

View File

@ -0,0 +1,115 @@
package com.simplemobiletools.camera
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Point
import android.hardware.Camera
import android.support.v4.content.ContextCompat
import android.widget.Toast
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class Utils {
companion object {
fun getCameraInfo(cameraId: Int): Camera.CameraInfo {
val info = android.hardware.Camera.CameraInfo()
Camera.getCameraInfo(cameraId, info)
return info
}
fun showToast(context: Context, resId: Int) {
Toast.makeText(context, context.resources.getString(resId), Toast.LENGTH_SHORT).show()
}
fun hasFlash(camera: Camera?): Boolean {
if (camera == null) {
return false
}
val parameters = camera.parameters
if (parameters.flashMode == null) {
return false
}
val supportedFlashModes = parameters.supportedFlashModes
if (supportedFlashModes == null || supportedFlashModes.isEmpty() ||
supportedFlashModes.size == 1 && supportedFlashModes[0] == Camera.Parameters.FLASH_MODE_OFF) {
return false
}
return true
}
fun getOutputMediaFile(context: Context, isPhoto: Boolean): String {
val mediaStorageDir = File(Config.newInstance(context).savePhotosFolder)
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return ""
}
}
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
if (isPhoto) {
return mediaStorageDir.path + File.separator + "IMG_" + timestamp + ".jpg"
} else {
return mediaStorageDir.path + File.separator + "VID_" + timestamp + ".mp4"
}
}
fun formatSeconds(duration: Int): String {
val sb = StringBuilder(8)
val hours = duration / (60 * 60)
val minutes = duration % (60 * 60) / 60
val seconds = duration % (60 * 60) % 60
if (duration > 3600000) {
sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":")
}
sb.append(String.format(Locale.getDefault(), "%02d", minutes))
sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds))
return sb.toString()
}
fun getScreenSize(activity: Activity): Point {
val display = activity.windowManager.defaultDisplay
val size = Point()
display.getSize(size)
size.y += getNavBarHeight(activity.resources)
return size
}
fun getNavBarHeight(res: Resources): Int {
val id = res.getIdentifier("navigation_bar_height", "dimen", "android")
if (id > 0 && hasNavBar(res)) {
return res.getDimensionPixelSize(id)
}
return 0
}
fun hasNavBar(res: Resources): Boolean {
val id = res.getIdentifier("config_showNavigationBar", "bool", "android")
return id > 0 && res.getBoolean(id)
}
fun hasCameraPermission(cxt: Context): Boolean {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
}
fun hasStoragePermission(cxt: Context): Boolean {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
}
fun hasAudioPermission(cxt: Context): Boolean {
return ContextCompat.checkSelfPermission(cxt, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
}
}
}

View File

@ -127,10 +127,10 @@ public class MainActivity extends SimpleActivity
handleIntent(); handleIntent();
} else { } else {
final List<String> permissions = new ArrayList<>(2); final List<String> permissions = new ArrayList<>(2);
if (!Utils.hasCameraPermission(getApplicationContext())) { if (!Utils.Companion.hasCameraPermission(getApplicationContext())) {
permissions.add(Manifest.permission.CAMERA); permissions.add(Manifest.permission.CAMERA);
} }
if (!Utils.hasStoragePermission(getApplicationContext())) { if (!Utils.Companion.hasStoragePermission(getApplicationContext())) {
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
} }
ActivityCompat.requestPermissions(this, permissions.toArray(new String[permissions.size()]), CAMERA_STORAGE_PERMISSION); ActivityCompat.requestPermissions(this, permissions.toArray(new String[permissions.size()]), CAMERA_STORAGE_PERMISSION);
@ -160,10 +160,10 @@ public class MainActivity extends SimpleActivity
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
ButterKnife.bind(this); ButterKnife.bind(this);
if (Utils.hasNavBar(getResources()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (Utils.Companion.hasNavBar(getResources()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final View btnLayout = findViewById(R.id.btn_holder); final View btnLayout = findViewById(R.id.btn_holder);
final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) btnLayout.getLayoutParams(); final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) btnLayout.getLayoutParams();
lp.setMargins(0, 0, 0, lp.bottomMargin + Utils.getNavBarHeight(getResources())); lp.setMargins(0, 0, 0, lp.bottomMargin + Utils.Companion.getNavBarHeight(getResources()));
} }
mCurrCamera = mConfig.getLastUsedCamera(); mCurrCamera = mConfig.getLastUsedCamera();
@ -184,7 +184,7 @@ public class MainActivity extends SimpleActivity
} }
private boolean hasCameraAndStoragePermission() { private boolean hasCameraAndStoragePermission() {
return Utils.hasCameraPermission(getApplicationContext()) && Utils.hasStoragePermission(getApplicationContext()); return Utils.Companion.hasCameraPermission(getApplicationContext()) && Utils.Companion.hasStoragePermission(getApplicationContext());
} }
@Override @Override
@ -197,14 +197,14 @@ public class MainActivity extends SimpleActivity
initializeCamera(); initializeCamera();
handleIntent(); handleIntent();
} else { } else {
Utils.showToast(getApplicationContext(), R.string.no_permissions); Utils.Companion.showToast(getApplicationContext(), R.string.no_permissions);
finish(); finish();
} }
} else if (requestCode == AUDIO_PERMISSION) { } else if (requestCode == AUDIO_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
togglePhotoVideo(); togglePhotoVideo();
} else { } else {
Utils.showToast(getApplicationContext(), R.string.no_audio_permissions); Utils.Companion.showToast(getApplicationContext(), R.string.no_audio_permissions);
if (mIsVideoCaptureIntent) if (mIsVideoCaptureIntent)
finish(); finish();
} }
@ -234,7 +234,7 @@ public class MainActivity extends SimpleActivity
disableFlash(); disableFlash();
hideTimer(); hideTimer();
} else { } else {
Utils.showToast(getApplicationContext(), R.string.camera_switch_error); Utils.Companion.showToast(getApplicationContext(), R.string.camera_switch_error);
} }
} }
@ -252,7 +252,7 @@ public class MainActivity extends SimpleActivity
if (intent.resolveActivity(getPackageManager()) != null) { if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent); startActivity(intent);
} else { } else {
Utils.showToast(getApplicationContext(), R.string.no_gallery_app_available); Utils.Companion.showToast(getApplicationContext(), R.string.no_gallery_app_available);
} }
} }
} }
@ -354,7 +354,7 @@ public class MainActivity extends SimpleActivity
return; return;
} }
if (!Utils.hasAudioPermission(getApplicationContext())) { if (!Utils.Companion.hasAudioPermission(getApplicationContext())) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_PERMISSION); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_PERMISSION);
mIsAskingPermissions = true; mIsAskingPermissions = true;
return; return;
@ -390,7 +390,7 @@ public class MainActivity extends SimpleActivity
initVideoButtons(); initVideoButtons();
} else { } else {
if (!mIsVideoCaptureIntent) { if (!mIsVideoCaptureIntent) {
Utils.showToast(getApplicationContext(), R.string.video_mode_error); Utils.Companion.showToast(getApplicationContext(), R.string.video_mode_error);
} }
} }
} }
@ -515,7 +515,7 @@ public class MainActivity extends SimpleActivity
} }
private void hideTimer() { private void hideTimer() {
mRecCurrTimer.setText(Utils.formatSeconds(0)); mRecCurrTimer.setText(Utils.Companion.formatSeconds(0));
mRecCurrTimer.setVisibility(View.GONE); mRecCurrTimer.setVisibility(View.GONE);
mCurrVideoRecTimer = 0; mCurrVideoRecTimer = 0;
mTimerHandler.removeCallbacksAndMessages(null); mTimerHandler.removeCallbacksAndMessages(null);
@ -530,7 +530,7 @@ public class MainActivity extends SimpleActivity
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
mRecCurrTimer.setText(Utils.formatSeconds(mCurrVideoRecTimer++)); mRecCurrTimer.setText(Utils.Companion.formatSeconds(mCurrVideoRecTimer++));
mTimerHandler.postDelayed(this, 1000); mTimerHandler.postDelayed(this, 1000);
} }
}); });
@ -570,7 +570,7 @@ public class MainActivity extends SimpleActivity
initVideoButtons(); initVideoButtons();
} }
} else { } else {
Utils.showToast(getApplicationContext(), R.string.camera_switch_error); Utils.Companion.showToast(getApplicationContext(), R.string.camera_switch_error);
} }
} }
@ -639,7 +639,7 @@ public class MainActivity extends SimpleActivity
private boolean checkCameraAvailable() { private boolean checkCameraAvailable() {
if (!mIsCameraAvailable) { if (!mIsCameraAvailable) {
Utils.showToast(getApplicationContext(), R.string.camera_unavailable); Utils.Companion.showToast(getApplicationContext(), R.string.camera_unavailable);
} }
return mIsCameraAvailable; return mIsCameraAvailable;
} }