diff --git a/app/build.gradle b/app/build.gradle index 32942d0..24d8a07 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,5 +1,4 @@ apply plugin: 'com.android.application' -apply plugin: 'android-apt' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' @@ -39,12 +38,8 @@ android { dependencies { compile 'com.simplemobiletools:commons:2.35.6' - compile 'com.jakewharton:butterknife:8.0.1' compile 'com.squareup:otto:1.3.8' - compile 'com.github.yukuku:ambilwarna:2.0.1' compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - - apt 'com.jakewharton:butterknife-compiler:8.0.1' } buildscript { diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 2cc1544..027d1b4 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -1,20 +1,3 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in $ANDROID_HOME/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} # Otto -keepattributes *Annotation* -keepclassmembers class ** { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a4ec6b4..d6147b0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -30,7 +30,7 @@ + android:theme="@style/AppTheme"/> { - startActivity(Intent(applicationContext, SettingsActivity::class.java)) - return true - } - R.id.about -> { - startActivity(Intent(applicationContext, AboutActivity::class.java)) - return true - } + R.id.settings -> launchSettings() + R.id.about -> launchAbout() else -> return super.onOptionsItemSelected(item) } + return true } private fun launchSettings() { @@ -105,88 +108,55 @@ class MainActivity : SimpleActivity() { mCameraImpl!!.enableFlashlight() } - @OnClick(R.id.toggle_btn) - fun toggleFlashlight() { - mCameraImpl!!.toggleFlashlight() - } + private fun setupStroboscope() { + stroboscope_btn.setOnClickListener { + toggleStroboscope() + } - @OnClick(R.id.bright_display_btn) - fun launchBrightDisplay() { - startActivity(Intent(applicationContext, BrightDisplayActivity::class.java)) - } + stroboscope_bar.max = MAX_STROBO_DELAY - MIN_STROBO_DELAY + stroboscope_bar.progress = stroboscope_bar.max / 2 + stroboscope_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, b: Boolean) { + val frequency = stroboscope_bar.max - progress + MIN_STROBO_DELAY + if (mCameraImpl != null) + mCameraImpl!!.stroboFrequency = frequency + } - @OnClick(R.id.stroboscope_btn) - fun tryToggleStroboscope() { - toggleStroboscope() + override fun onStartTrackingTouch(seekBar: SeekBar) { + + } + + override fun onStopTrackingTouch(seekBar: SeekBar) { + + } + }) } private fun toggleStroboscope() { // use the old Camera API for stroboscope, the new Camera Manager is way too slow - if (isCameraPermissionGranted || Utils.isNougat) { - if (mCameraImpl!!.toggleStroboscope()) { - stroboscope_bar.visibility = if (stroboscope_bar.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE - changeIconColor(if (stroboscope_bar.visibility == View.VISIBLE) R.color.colorPrimary else R.color.translucent_white, stroboscope_btn) - } + if (isNougatPlus()) { + cameraPermissionGranted() } else { - val permissions = arrayOf(Manifest.permission.CAMERA) - ActivityCompat.requestPermissions(this, permissions, CAMERA_PERMISSION) - } - } - - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults) - - if (requestCode == CAMERA_PERMISSION) { - mJustGrantedPermission = true - if (isCameraPermissionGranted) { - toggleStroboscope() - } else { - Utils.showToast(applicationContext, R.string.camera_permission) + handlePermission(PERMISSION_CAMERA) { + if (it) { + cameraPermissionGranted() + } else { + toast(R.string.camera_permission) + } } } } - override fun onStart() { - super.onStart() - mBus!!.register(this) - - if (mCameraImpl == null) { - setupCameraImpl() + private fun cameraPermissionGranted() { + if (mCameraImpl!!.toggleStroboscope()) { + stroboscope_bar.beInvisibleIf(stroboscope_bar.visibility == View.VISIBLE) + changeIconColor(if (stroboscope_bar.visibility == View.VISIBLE) R.color.color_primary else R.color.translucent_white, stroboscope_btn) } } - override fun onResume() { - super.onResume() - if (mJustGrantedPermission) { - mJustGrantedPermission = false - return - } - mCameraImpl!!.handleCameraSetup() - mCameraImpl!!.checkFlashlight() - - bright_display_btn!!.visibility = if (config.brightDisplay) View.VISIBLE else View.GONE - stroboscope_btn!!.visibility = if (config.stroboscope) View.VISIBLE else View.GONE - if (!config.stroboscope) { - mCameraImpl!!.stopStroboscope() - stroboscope_bar.visibility = View.INVISIBLE - } - } - - override fun onStop() { - super.onStop() - mBus!!.unregister(this) - } - - override fun onDestroy() { - super.onDestroy() - releaseCamera() - } - private fun releaseCamera() { - if (mCameraImpl != null) { - mCameraImpl!!.releaseCamera() - mCameraImpl = null - } + mCameraImpl?.releaseCamera() + mCameraImpl = null } @Subscribe @@ -198,15 +168,15 @@ class MainActivity : SimpleActivity() { } } - fun enableFlashlight() { - changeIconColor(R.color.colorPrimary, toggle_btn) + private fun enableFlashlight() { + changeIconColor(R.color.color_primary, toggle_btn) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) changeIconColor(R.color.translucent_white, stroboscope_btn) stroboscope_bar.beInvisible() } - fun disableFlashlight() { + private fun disableFlashlight() { changeIconColor(R.color.translucent_white, toggle_btn) window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } @@ -218,7 +188,7 @@ class MainActivity : SimpleActivity() { @Subscribe fun cameraUnavailable(event: Events.CameraUnavailable) { - Utils.showToast(this, R.string.camera_error) + toast(R.string.camera_error) disableFlashlight() } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/SettingsActivity.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/SettingsActivity.kt index 62a0a54..240ec3c 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/SettingsActivity.kt @@ -1,54 +1,45 @@ package com.simplemobiletools.flashlight.activities import android.os.Bundle -import android.support.v4.app.TaskStackBuilder -import android.support.v7.widget.SwitchCompat -import butterknife.BindView -import butterknife.ButterKnife -import butterknife.OnClick +import com.simplemobiletools.commons.extensions.updateTextColors import com.simplemobiletools.flashlight.R -import com.simplemobiletools.flashlight.helpers.Config +import com.simplemobiletools.flashlight.extensions.config +import kotlinx.android.synthetic.main.activity_settings.* class SettingsActivity : SimpleActivity() { - @BindView(R.id.settings_bright_display) internal var mBrightDisplaySwitch: SwitchCompat? = null - @BindView(R.id.settings_stroboscope) internal var mStroboscopeSwitch: SwitchCompat? = null - override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) - mConfig = Config.newInstance(applicationContext) - ButterKnife.bind(this) + } + override fun onResume() { + super.onResume() + + setupCustomizeColors() setupBrightDisplay() setupStroboscope() + updateTextColors(settings_holder) + } + + private fun setupCustomizeColors() { + settings_customize_colors_holder.setOnClickListener { + startCustomizationActivity() + } } private fun setupBrightDisplay() { - mBrightDisplaySwitch!!.isChecked = mConfig!!.brightDisplay + settings_bright_display.isChecked = config.brightDisplay + settings_bright_display_holder.setOnClickListener { + settings_bright_display.toggle() + config.brightDisplay = settings_bright_display.isChecked + } } private fun setupStroboscope() { - mStroboscopeSwitch!!.isChecked = mConfig!!.stroboscope - } - - @OnClick(R.id.settings_bright_display_holder) - fun handleBrightDisplay() { - mBrightDisplaySwitch!!.isChecked = !mBrightDisplaySwitch!!.isChecked - mConfig!!.brightDisplay = mBrightDisplaySwitch!!.isChecked - } - - @OnClick(R.id.settings_stroboscope_holder) - fun handleStroboscope() { - mStroboscopeSwitch!!.isChecked = !mStroboscopeSwitch!!.isChecked - mConfig!!.stroboscope = mStroboscopeSwitch!!.isChecked - } - - private fun restartActivity() { - TaskStackBuilder.create(applicationContext).addNextIntentWithParentStack(intent).startActivities() - } - - companion object { - - private var mConfig: Config? = null + settings_stroboscope.isChecked = config.stroboscope + settings_stroboscope_holder.setOnClickListener { + settings_stroboscope.toggle() + config.stroboscope = settings_stroboscope.isChecked + } } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/WidgetConfigureActivity.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/WidgetConfigureActivity.kt index 743775e..d55a1ce 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/WidgetConfigureActivity.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/activities/WidgetConfigureActivity.kt @@ -8,23 +8,95 @@ import android.graphics.Color import android.graphics.PorterDuff import android.os.Bundle import android.support.v7.app.AppCompatActivity -import android.view.View -import android.widget.ImageView import android.widget.RemoteViews import android.widget.SeekBar -import butterknife.BindView -import butterknife.ButterKnife -import butterknife.OnClick +import com.simplemobiletools.commons.dialogs.ColorPickerDialog +import com.simplemobiletools.commons.extensions.adjustAlpha import com.simplemobiletools.commons.helpers.PREFS_KEY import com.simplemobiletools.flashlight.R import com.simplemobiletools.flashlight.helpers.MyWidgetProvider import com.simplemobiletools.flashlight.helpers.WIDGET_COLOR -import yuku.ambilwarna.AmbilWarnaDialog +import kotlinx.android.synthetic.main.widget_config.* class WidgetConfigureActivity : AppCompatActivity() { - @BindView(R.id.config_widget_seekbar) internal var mWidgetSeekBar: SeekBar? = null - @BindView(R.id.config_widget_color) internal var mWidgetColorPicker: View? = null - @BindView(R.id.config_image) internal var mImage: ImageView? = null + companion object { + private var mWidgetAlpha = 0f + private var mWidgetId = 0 + private var mWidgetColor = 0 + private var mWidgetColorWithoutTransparency = 0 + } + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setResult(Activity.RESULT_CANCELED) + setContentView(R.layout.widget_config) + initVariables() + + val intent = intent + val extras = intent.extras + if (extras != null) + mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) + + if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) + finish() + + config_save.setOnClickListener { saveConfig() } + config_widget_color.setOnClickListener { pickBackgroundColor() } + } + + private fun initVariables() { + val prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) + mWidgetColor = prefs.getInt(WIDGET_COLOR, 1) + if (mWidgetColor == 1) { + mWidgetColor = resources.getColor(R.color.color_primary) + mWidgetAlpha = 1f + } else { + mWidgetAlpha = Color.alpha(mWidgetColor) / 255.toFloat() + } + + mWidgetColorWithoutTransparency = Color.rgb(Color.red(mWidgetColor), Color.green(mWidgetColor), Color.blue(mWidgetColor)) + config_widget_seekbar.setOnSeekBarChangeListener(seekbarChangeListener) + config_widget_seekbar.progress = (mWidgetAlpha * 100).toInt() + updateColors() + } + + fun saveConfig() { + val appWidgetManager = AppWidgetManager.getInstance(this) + val views = RemoteViews(packageName, R.layout.widget) + appWidgetManager.updateAppWidget(mWidgetId, views) + + storeWidgetColors() + requestWidgetUpdate() + + val resultValue = Intent() + resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId) + setResult(Activity.RESULT_OK, resultValue) + finish() + } + + fun pickBackgroundColor() { + ColorPickerDialog(this, mWidgetColorWithoutTransparency) { + mWidgetColorWithoutTransparency = it + updateColors() + } + } + + private fun storeWidgetColors() { + val prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) + prefs.edit().putInt(WIDGET_COLOR, mWidgetColor).apply() + } + + private fun requestWidgetUpdate() { + val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java) + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId)) + sendBroadcast(intent) + } + + private fun updateColors() { + mWidgetColor = mWidgetColorWithoutTransparency.adjustAlpha(mWidgetAlpha) + config_widget_color.setBackgroundColor(mWidgetColor) + config_image.background.mutate().setColorFilter(mWidgetColor, PorterDuff.Mode.SRC_IN) + } private val seekbarChangeListener = object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { @@ -40,98 +112,4 @@ class WidgetConfigureActivity : AppCompatActivity() { } } - - public override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setResult(Activity.RESULT_CANCELED) - setContentView(R.layout.widget_config) - ButterKnife.bind(this) - initVariables() - - val intent = intent - val extras = intent.extras - if (extras != null) - mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) - - if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) - finish() - } - - private fun initVariables() { - val prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) - mWidgetColor = prefs.getInt(WIDGET_COLOR, 1) - if (mWidgetColor == 1) { - mWidgetColor = resources.getColor(R.color.colorPrimary) - mWidgetAlpha = 1f - } else { - mWidgetAlpha = Color.alpha(mWidgetColor) / 255.toFloat() - } - - mWidgetColorWithoutTransparency = Color.rgb(Color.red(mWidgetColor), Color.green(mWidgetColor), Color.blue(mWidgetColor)) - mWidgetSeekBar!!.setOnSeekBarChangeListener(seekbarChangeListener) - mWidgetSeekBar!!.progress = (mWidgetAlpha * 100).toInt() - updateColors() - } - - @OnClick(R.id.config_save) - fun saveConfig() { - val appWidgetManager = AppWidgetManager.getInstance(this) - val views = RemoteViews(packageName, R.layout.widget) - appWidgetManager.updateAppWidget(mWidgetId, views) - - storeWidgetColors() - requestWidgetUpdate() - - val resultValue = Intent() - resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId) - setResult(Activity.RESULT_OK, resultValue) - finish() - } - - @OnClick(R.id.config_widget_color) - fun pickBackgroundColor() { - val dialog = AmbilWarnaDialog(this, mWidgetColorWithoutTransparency, object : AmbilWarnaDialog.OnAmbilWarnaListener { - override fun onCancel(dialog: AmbilWarnaDialog) {} - - override fun onOk(dialog: AmbilWarnaDialog, color: Int) { - mWidgetColorWithoutTransparency = color - updateColors() - } - }) - - dialog.show() - } - - private fun storeWidgetColors() { - val prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) - prefs.edit().putInt(WIDGET_COLOR, mWidgetColor).apply() - } - - private fun requestWidgetUpdate() { - val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java) - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId)) - sendBroadcast(intent) - } - - private fun updateColors() { - mWidgetColor = adjustAlpha(mWidgetColorWithoutTransparency, mWidgetAlpha) - mWidgetColorPicker!!.setBackgroundColor(mWidgetColor) - mImage!!.background.mutate().setColorFilter(mWidgetColor, PorterDuff.Mode.SRC_IN) - } - - private fun adjustAlpha(color: Int, factor: Float): Int { - val alpha = Math.round(Color.alpha(color) * factor) - val red = Color.red(color) - val green = Color.green(color) - val blue = Color.blue(color) - return Color.argb(alpha, red, green, blue) - } - - companion object { - - private var mWidgetAlpha: Float = 0.toFloat() - private var mWidgetId: Int = 0 - private var mWidgetColor: Int = 0 - private var mWidgetColorWithoutTransparency: Int = 0 - } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MarshmallowCamera.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MarshmallowCamera.kt index f7623e0..8de3bf9 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MarshmallowCamera.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MarshmallowCamera.kt @@ -6,25 +6,20 @@ import android.hardware.camera2.CameraAccessException import android.hardware.camera2.CameraManager import android.os.Build import android.os.Handler -import android.util.Log - import com.simplemobiletools.flashlight.models.Events import com.squareup.otto.Bus -internal class MarshmallowCamera @TargetApi(Build.VERSION_CODES.M) -constructor(private val mContext: Context) { +@TargetApi(Build.VERSION_CODES.LOLLIPOP) +internal class MarshmallowCamera constructor(val context: Context) { - private val manager: CameraManager + private val manager: CameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager private var cameraId: String? = null init { - manager = mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager try { - val list = manager.cameraIdList - cameraId = list[0] + cameraId = manager.cameraIdList[0] } catch (ignored: CameraAccessException) { } - } @TargetApi(Build.VERSION_CODES.M) @@ -32,15 +27,10 @@ constructor(private val mContext: Context) { try { manager.setTorchMode(cameraId!!, enable) } catch (e: CameraAccessException) { - Log.e(TAG, "toggle marshmallow flashlight " + e.message) - - val mainRunnable = Runnable { bus.post(Events.CameraUnavailable()) } - Handler(mContext.mainLooper).post(mainRunnable) + val mainRunnable = Runnable { + bus.post(Events.CameraUnavailable()) + } + Handler(context.mainLooper).post(mainRunnable) } - - } - - companion object { - private val TAG = MyCameraImpl::class.java.simpleName } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyCameraImpl.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyCameraImpl.kt index 6ca304f..183d59b 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyCameraImpl.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyCameraImpl.kt @@ -1,109 +1,104 @@ package com.simplemobiletools.flashlight.helpers +import android.annotation.TargetApi import android.content.Context import android.graphics.SurfaceTexture import android.hardware.Camera +import android.os.Build import android.os.Handler -import android.util.Log - +import com.simplemobiletools.commons.extensions.isMarshmallowPlus +import com.simplemobiletools.commons.extensions.isNougatPlus +import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.flashlight.R import com.simplemobiletools.flashlight.models.Events import com.squareup.otto.Bus - import java.io.IOException -class MyCameraImpl(private val mContext: Context) { +class MyCameraImpl(val context: Context) { + var stroboFrequency = 1000 + companion object { - private val TAG = MyCameraImpl::class.java.simpleName - - private var mCamera: Camera? = null + private var camera: Camera? = null private var mParams: Camera.Parameters? = null - private var mBus: Bus? = null + private var bus: Bus? = null - private var mIsFlashlightOn: Boolean = false - private var mIsMarshmallow: Boolean = false - private var mShouldEnableFlashlight: Boolean = false - private var mStroboFrequency: Int = 0 + private var mIsFlashlightOn = false + private var mIsMarshmallow = false + private var mShouldEnableFlashlight = false } - private var mMarshmallowCamera: MarshmallowCamera? = null - @Volatile private var mShouldStroboscopeStop: Boolean = false - @Volatile private var mIsStroboscopeRunning: Boolean = false - - private val isMarshmallow: Boolean - get() = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M + private var marshmallowCamera: MarshmallowCamera? = null + @Volatile private var shouldStroboscopeStop = false + @Volatile private var isStroboscopeRunning = false private val stroboscope = Runnable { - if (mIsStroboscopeRunning) { + if (isStroboscopeRunning) { return@Runnable } - mShouldStroboscopeStop = false - mIsStroboscopeRunning = true + shouldStroboscopeStop = false + isStroboscopeRunning = true - if (Utils.isNougat) { - while (!mShouldStroboscopeStop) { + if (context.isNougatPlus()) { + while (!shouldStroboscopeStop) { try { - mMarshmallowCamera!!.toggleMarshmallowFlashlight(mBus!!, true) - Thread.sleep(mStroboFrequency.toLong()) - mMarshmallowCamera!!.toggleMarshmallowFlashlight(mBus!!, false) - Thread.sleep(mStroboFrequency.toLong()) + marshmallowCamera!!.toggleMarshmallowFlashlight(bus!!, true) + Thread.sleep(stroboFrequency.toLong()) + marshmallowCamera!!.toggleMarshmallowFlashlight(bus!!, false) + Thread.sleep(stroboFrequency.toLong()) } catch (ignored: InterruptedException) { - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } catch (ignored: RuntimeException) { - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } } } else { - if (mCamera == null) { + if (camera == null) { initCamera() } - val torchOn = mCamera!!.parameters - val torchOff = mCamera!!.parameters + val torchOn = camera!!.parameters + val torchOff = camera!!.parameters torchOn.flashMode = Camera.Parameters.FLASH_MODE_TORCH torchOff.flashMode = Camera.Parameters.FLASH_MODE_OFF val dummy = SurfaceTexture(1) try { - mCamera!!.setPreviewTexture(dummy) + camera!!.setPreviewTexture(dummy) } catch (e: IOException) { - Log.e(TAG, "setup stroboscope1 " + e.message) } - mCamera!!.startPreview() + camera!!.startPreview() - while (!mShouldStroboscopeStop) { + while (!shouldStroboscopeStop) { try { - mCamera!!.parameters = torchOn - Thread.sleep(mStroboFrequency.toLong()) - mCamera!!.parameters = torchOff - Thread.sleep(mStroboFrequency.toLong()) + camera!!.parameters = torchOn + Thread.sleep(stroboFrequency.toLong()) + camera!!.parameters = torchOff + Thread.sleep(stroboFrequency.toLong()) } catch (ignored: InterruptedException) { - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } catch (ignored: RuntimeException) { - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } } try { - if (mCamera != null) { - mCamera!!.parameters = torchOff + if (camera != null) { + camera!!.parameters = torchOff if (!mShouldEnableFlashlight || mIsMarshmallow) { - mCamera!!.release() - mCamera = null + camera!!.release() + camera = null } } } catch (e: RuntimeException) { - Log.e(TAG, "setup stroboscope2 " + e.message) } - } - mIsStroboscopeRunning = false - mShouldStroboscopeStop = false + isStroboscopeRunning = false + shouldStroboscopeStop = false if (mShouldEnableFlashlight) { enableFlashlight() @@ -112,12 +107,11 @@ class MyCameraImpl(private val mContext: Context) { } init { - mIsMarshmallow = isMarshmallow - mStroboFrequency = 1000 + mIsMarshmallow = context.isMarshmallowPlus() - if (mBus == null) { - mBus = BusProvider.instance - mBus!!.register(this) + if (bus == null) { + bus = BusProvider.instance + bus!!.register(this) } handleCameraSetup() @@ -129,26 +123,22 @@ class MyCameraImpl(private val mContext: Context) { handleCameraSetup() } - fun setStroboFrequency(frequency: Int) { - mStroboFrequency = frequency - } - fun toggleStroboscope(): Boolean { - if (!mIsStroboscopeRunning) + if (!isStroboscopeRunning) disableFlashlight() - if (!Utils.isNougat) { - if (mCamera == null) { + if (!context.isNougatPlus()) { + if (camera == null) { initCamera() } - if (mCamera == null) { - Utils.showToast(mContext, R.string.camera_error) + if (camera == null) { + context.toast(R.string.camera_error) return false } } - if (mIsStroboscopeRunning) { + if (isStroboscopeRunning) { stopStroboscope() } else { Thread(stroboscope).start() @@ -157,7 +147,7 @@ class MyCameraImpl(private val mContext: Context) { } fun stopStroboscope() { - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } fun handleCameraSetup() { @@ -170,8 +160,8 @@ class MyCameraImpl(private val mContext: Context) { } private fun setupMarshmallowCamera() { - if (mMarshmallowCamera == null) { - mMarshmallowCamera = MarshmallowCamera(mContext) + if (marshmallowCamera == null) { + marshmallowCamera = MarshmallowCamera(context) } } @@ -179,20 +169,19 @@ class MyCameraImpl(private val mContext: Context) { if (mIsMarshmallow) return - if (mCamera == null) { + if (camera == null) { initCamera() } } private fun initCamera() { try { - mCamera = Camera.open() - mParams = mCamera!!.parameters + camera = Camera.open() + mParams = camera!!.parameters mParams!!.flashMode = Camera.Parameters.FLASH_MODE_OFF - mCamera!!.parameters = mParams + camera!!.parameters = mParams } catch (e: Exception) { - Log.e(TAG, "setup mCamera " + e.message) - mBus!!.post(Events.CameraUnavailable()) + bus!!.post(Events.CameraUnavailable()) } } @@ -206,8 +195,8 @@ class MyCameraImpl(private val mContext: Context) { } fun enableFlashlight() { - mShouldStroboscopeStop = true - if (mIsStroboscopeRunning) { + shouldStroboscopeStop = true + if (isStroboscopeRunning) { mShouldEnableFlashlight = true return } @@ -216,21 +205,21 @@ class MyCameraImpl(private val mContext: Context) { if (mIsMarshmallow) { toggleMarshmallowFlashlight(true) } else { - if (mCamera == null || mParams == null) { + if (camera == null || mParams == null) { return } mParams!!.flashMode = Camera.Parameters.FLASH_MODE_TORCH - mCamera!!.parameters = mParams - mCamera!!.startPreview() + camera!!.parameters = mParams + camera!!.startPreview() } - val mainRunnable = Runnable { mBus!!.post(Events.StateChanged(true)) } - Handler(mContext.mainLooper).post(mainRunnable) + val mainRunnable = Runnable { bus!!.post(Events.StateChanged(true)) } + Handler(context.mainLooper).post(mainRunnable) } private fun disableFlashlight() { - if (mIsStroboscopeRunning) { + if (isStroboscopeRunning) { return } @@ -238,18 +227,18 @@ class MyCameraImpl(private val mContext: Context) { if (mIsMarshmallow) { toggleMarshmallowFlashlight(false) } else { - if (mCamera == null || mParams == null) { + if (camera == null || mParams == null) { return } mParams!!.flashMode = Camera.Parameters.FLASH_MODE_OFF - mCamera!!.parameters = mParams + camera!!.parameters = mParams } - mBus!!.post(Events.StateChanged(false)) + bus!!.post(Events.StateChanged(false)) } private fun toggleMarshmallowFlashlight(enable: Boolean) { - mMarshmallowCamera!!.toggleMarshmallowFlashlight(mBus!!, enable) + marshmallowCamera!!.toggleMarshmallowFlashlight(bus!!, enable) } fun releaseCamera() { @@ -257,15 +246,11 @@ class MyCameraImpl(private val mContext: Context) { disableFlashlight() } - if (mCamera != null) { - mCamera!!.release() - mCamera = null - } + camera?.release() + camera = null - if (mBus != null) { - mBus!!.unregister(this) - } + bus?.unregister(this) mIsFlashlightOn = false - mShouldStroboscopeStop = true + shouldStroboscopeStop = true } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyWidgetProvider.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyWidgetProvider.kt index 7dc9e7a..81b4b0e 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyWidgetProvider.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyWidgetProvider.kt @@ -11,6 +11,7 @@ import android.graphics.Bitmap import android.graphics.Color import android.graphics.PorterDuff import android.widget.RemoteViews +import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.commons.helpers.PREFS_KEY import com.simplemobiletools.flashlight.R import com.simplemobiletools.flashlight.models.Events @@ -40,7 +41,7 @@ class MyWidgetProvider : AppWidgetProvider() { val prefs = initPrefs(context) val res = context.resources - val defaultColor = res.getColor(R.color.colorPrimary) + val defaultColor = res.getColor(R.color.color_primary) val selectedColor = prefs.getInt(WIDGET_COLOR, defaultColor) val alpha = Color.alpha(selectedColor) @@ -94,7 +95,7 @@ class MyWidgetProvider : AppWidgetProvider() { @Subscribe fun cameraUnavailable(event: Events.CameraUnavailable) { if (mContext != null) { - Utils.showToast(mContext!!, R.string.camera_error) + mContext!!.toast(R.string.camera_error) disableFlashlight() } } diff --git a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/Utils.kt b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/Utils.kt index 58e6222..fa08921 100644 --- a/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/Utils.kt +++ b/app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/Utils.kt @@ -1,17 +1,11 @@ package com.simplemobiletools.flashlight.helpers -import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable -import android.os.Build -import android.widget.Toast object Utils { - val isNougat: Boolean - get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N - fun drawableToBitmap(drawable: Drawable): Bitmap { val width = drawable.intrinsicWidth val height = drawable.intrinsicHeight @@ -21,8 +15,4 @@ object Utils { drawable.draw(canvas) return mutableBitmap } - - fun showToast(context: Context, resId: Int) { - Toast.makeText(context, context.resources.getString(resId), Toast.LENGTH_SHORT).show() - } } diff --git a/app/src/main/res/layout/activity_bright_display.xml b/app/src/main/res/layout/activity_bright_display.xml index dd040f9..447f4df 100644 --- a/app/src/main/res/layout/activity_bright_display.xml +++ b/app/src/main/res/layout/activity_bright_display.xml @@ -1,7 +1,7 @@ diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index 57cf3f7..d4daeac 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -12,28 +12,41 @@ android:orientation="vertical"> - + android:paddingLeft="@dimen/medium_margin" + android:paddingStart="@dimen/medium_margin" + android:text="@string/customize_colors"/> - + + + + + android:clickable="false" + android:paddingLeft="@dimen/medium_margin" + android:paddingStart="@dimen/medium_margin" + android:text="@string/bright_display"/> @@ -41,25 +54,19 @@ android:id="@+id/settings_stroboscope_holder" android:layout_width="match_parent" android:layout_height="wrap_content" - android:layout_marginTop="@dimen/settings_padding" + android:layout_marginTop="@dimen/medium_margin" android:background="?attr/selectableItemBackground" android:padding="@dimen/activity_margin"> - - - + android:clickable="false" + android:paddingLeft="@dimen/medium_margin" + android:paddingStart="@dimen/medium_margin" + android:text="@string/show_stroboscope"/> diff --git a/app/src/main/res/layout/widget_config.xml b/app/src/main/res/layout/widget_config.xml index 4a0283f..8088c5d 100644 --- a/app/src/main/res/layout/widget_config.xml +++ b/app/src/main/res/layout/widget_config.xml @@ -56,7 +56,7 @@ android:paddingLeft="@dimen/activity_margin" android:paddingRight="@dimen/activity_margin" android:text="@string/ok" - android:textColor="@color/colorPrimary" - android:textSize="@dimen/config_text_size"/> + android:textColor="@color/color_primary" + android:textSize="@dimen/big_text_size"/> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 6d13735..7200633 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2,34 +2,12 @@ Schlichte Taschenlampe Taschenlampe Beanspruchen der Kamera fehlgeschlagen - OK Kamera-Berechtigung ist für den Stroboskopeffekt erforderlich - Einstellungen - Dunkles Design Zeige Button für helles Display Zeige Button für Stroboskop - - Über - Weitere einfache Apps und Quellcode findest du auf:\nhttp://simplemobiletools.com - Sende Vorschläge und Feedback an: - Drittanbieterlizenzen - Freunde einladen - Hey, wirf mal einen Blick auf %1$s: %2$s - Einladen via - Bewerte uns im Play Store - Folge uns: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - Diese App nutzt die folgenden Drittanbieterbibliotheken, die mein Leben einfacher machen. Danke. - Drittanbieterlizenzen - Butter Knife (View Injector) - AmbilWarna (Color Picker) - Otto (Event Bus) - Eine schlichte Taschenlampe ohne Werbung. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index f461200..492fe38 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2,40 +2,13 @@ Simple Flashlight Linterna Ha fallado el acceso a la cámara - Ok El permiso de acceso a la cámara es necesario para un apropiado efecto estroboscópico - - Opciones - Tema oscuro - Mostrar un botón de brillo - Mostrar un botón de estroboscopio - - - Acerca de Simple Flashlight - Más aplicaciones simples y su código fuente en:\nhttp://simplemobiletools.com - Envíe sus comentarios y sugerencias a: - Licencias de terceros - Invitar a amigos - Hola, venga y échele un vistazo a %1$s en %2$s - Invitar vía - Evalúenos en Google Play Store - Síganos: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - Esta aplicación usa las siguientes librerías de terceros para hacerme la vida más fácil. Gracias. - Licencias de terceros - Butter Knife (Inyector de vistas) - AmbilWarna (Selector de colores) - Otto (Canal de eventos) - Una simple linterna sin anuncios. Una sencilla linterna con brillo extra de pantalla y un personalizable estroboscopio. Si la enciende a través de la aplicación (no del widget), prevendrá que el dispositivo se duerma. - Viene con un widget 1x1 con color personalizable. No contiene anuncios ni permisos innecesarios. Es completamente OpenSource y además provee un tema oscuro. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f65c2be..7a8c05e 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2,40 +2,17 @@ Simple Flashlight Flashlight Rilevamento fotocamera fallito - OK Camera permission is necessary for proper stroboscope effect - Impostazioni - Tema scuro Mostra un pulsante per schermo luminoso Show a stroboscope button - - Informazioni - Altre semplici app e codici sorgenti in:\nhttp://simplemobiletools.com - Invia la tua opinione o i tuoi suggerimenti a: - Licenze di terze parti - Invite friends - Hey, come check out %1$s at %2$s - Invite via - Dacci un voto sul Play Store - Seguici: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - Questa app usa le seguenti librerie di terze parti per semplificarmi la vita. Grazie. - Licenze di terze parti - Butter Knife (view injector) - AmbilWarna (color picker) - Otto (event bus) - A simple flashlight without ads. A clean flashlight with an extra bright display and customizable stroboscope. If turned on via the app (not widget), it will prevent the device from falling asleep. - Comes with a 1x1 widget with customizable color. Contains no ads or unnecessary permissions. It is fully opensource, provides a Dark theme too. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index c3a6cec..108e5e9 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2,40 +2,17 @@ シンプル フラッシュライト フラッシュライト カメラの取得に失敗しました - OK 適切なストロボ効果のために、カメラのアクセス許可が必要です - 設定 - ダークテーマ 明るく表示ボタンを表示 ストロボボタンを表示 - - アプリについて - もっとシンプルなアプリとソースコード:\nhttp://simplemobiletools.com - ご意見やご提案を送信してください: - サードパーティー ライセンス - 友達を招待 - %2$s で %1$s を確認してください - 招待... - Play ストアで評価してください - フォローしてください: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - このアプリは、私の暮らしにゆとりを持たせるために、次のサードパーティのライブラリーを使用しています。 ありがとうございます。 - サードパーティー ライセンス - Butter Knife (ビュー インジェクター) - AmbilWarna (カラー ピッカー) - Otto (イベント バス) - 広告のないシンプルな懐中電灯です。 特別に明るく表示とカスタマイズ可能なストロボを備えたシンプルな懐中電灯です。 (ウィジェットではなく)アプリでオンにすると、デバイスがスリープ状態にならないようになります。 - カスタマイズ可能な色の 1x1 ウィジェットが付属しています。 広告や不要なアクセス許可は含まれていません。 完全にオープンソースで、ダークテーマも提供しています。 diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 622ae08..a4f16ff 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2,40 +2,17 @@ Simple Flashlight Lanterna Falha ao obter a câmara - OK A permissão da câmara é necessária para utilizar o efeito estroboscópico - Definições - Tema escuro Mostrar botão para iluminar o ecrã Mostrar botão de estroboscópio - - Acerca - Mais aplicações Simple e código fonte em:\nhttp://simplemobiletools.com - Envie os seus comentários ou sugestões para: - Licenças de terceiros - Convidar amigos - Olá, experimenta %1$s em %2$s - Convidar via - Avalie-nos na Play Store - Siga-nos: - V %1$s\nCopyright © Simple Mobile Tools %2$d - - - Esta aplicação usa as seguintes bibliotecas de terceiros para facilitar a minha vida. Obrigado. - Licenças de terceiros - Butter Knife (injetor de vistas) - AmbilWarna (selector de sores) - Otto (canal de eventos) - Um lanterna básica. Uma lanterna simples com um brilho extra e um estroboscópio personalizável. Pode ser ativada na aplicação (não no widget), impedindo o adormecimento do dispositivo. - Disponibiliza um widget 1x1 com uma cor personalizável. Não contém anúncios nem permissões desnecessárias. Disponibiliza um tema escuro e é totalmente \'open source\'. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 0070a6a..98e8e3e 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2,40 +2,17 @@ Simple Flashlight Ficklampa Det gick inte att komma åt kameran - OK Kamerabehörigheten behövs för en riktig stroboskopeffekt - Inställningar - Mörkt tema Visa en knapp för ljus skärm Visa en stroboskopknapp - - Om - Fler enkla appar och källkod här:\nhttp://simplemobiletools.com - Skicka feedback och förslag till: - Tredjepartslicenser - Bjud in vänner - Hej, läs om %1$s på %2$s - Bjud in via - Betygsätt oss i Play Butiken - Följ oss: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - Denna app använder följande tredjepartsbibliotek för att göra mitt liv enklare. Tack. - Tredjepartslicenser - Butter Knife (vyinjektor) - AmbilWarna (färgväljare) - Otto (händelsebuss) - En enkel ficklampa utan reklam. En ren ficklampa med en extra ljus skärm och ett anpassningsbart stroboskop. Om den slås på via appen (inte widgeten), hindrar den enheten från att försättas i viloläge. - Har en 1x1-widget med anpassningsbar färg. Innehåller ingen reklam eller onödiga behörigheter. Den har helt öppen källkod och har även ett Mörkt tema. diff --git a/app/src/main/res/values-sw600dp/dimens.xml b/app/src/main/res/values-sw600dp/dimens.xml deleted file mode 100644 index 15f0bf0..0000000 --- a/app/src/main/res/values-sw600dp/dimens.xml +++ /dev/null @@ -1,6 +0,0 @@ - - 12dp - 50dp - - 18sp - diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 8e5243c..7149e29 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -1,8 +1,5 @@ - #fff68630 - #ffe27725 - @color/colorPrimary #eeffffff #88000000 diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml index 0ee4adf..bdf7c3c 100644 --- a/app/src/main/res/values/dimens.xml +++ b/app/src/main/res/values/dimens.xml @@ -1,13 +1,6 @@ - 16dp 30dp - 8dp - 40dp - 8dp 250dp 6dp 150dp - - 14sp - 18sp diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 793e8e9..3a8fd64 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2,50 +2,20 @@ Simple Flashlight Flashlight Obtaining the camera failed - OK Camera permission is necessary for proper stroboscope effect - Settings - Dark theme Show a bright display button Show a stroboscope button - - About - More simple apps and source code at:\nhttp://simplemobiletools.com - Send your feedback or suggestions to: - hello@simplemobiletools.com - Third party licenses - Invite friends - Hey, come check out %1$s at %2$s - Invite via - Rate us in the Play Store - Follow us: - v %1$s\nCopyright © Simple Mobile Tools %2$d - - - This app uses the following third party libraries to make my life easier. Thank you. - Third party licenses - Butter Knife (view injector) - Copyright 2013 Jake Wharton\n\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - https://github.com/JakeWharton/butterknife - AmbilWarna (color picker) - Copyright 2009-2015 Yuku\n\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - https://github.com/yukuku/ambilwarna - Otto (event bus) - Copyright 2012 Square, Inc.\nCopyright 2010 Google, Inc.\n\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - https://github.com/square/otto - A simple flashlight without ads. A clean flashlight with an extra bright display and customizable stroboscope. If turned on via the app (not widget), it will prevent the device from falling asleep. - Comes with a 1x1 widget with customizable color. - Contains no ads or unnecessary permissions. It is fully opensource, provides a Dark theme too. + Contains no ads or unnecessary permissions. It is fully opensource, provides customizable colors. This app is just one piece of a bigger series of apps. You can find the rest of them at http://www.simplemobiletools.com diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index ed34ff0..0be5041 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -1,38 +1,5 @@ - + - - - - - - - - diff --git a/app/src/main/res/xml/widget_info.xml b/app/src/main/res/xml/widget_info.xml index 9a591b9..4e35808 100644 --- a/app/src/main/res/xml/widget_info.xml +++ b/app/src/main/res/xml/widget_info.xml @@ -1,7 +1,8 @@ - + diff --git a/build.gradle b/build.gradle index eedc9ad..633d203 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,6 @@ buildscript { } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' - classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files