如何在Android中使用Kotlin为Java创建函数之间的无限循环?

huangapple go评论64阅读模式
英文:

How make endless loop between functions using Kotlin for Java in Android?

问题

package com.example.flashlight

import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    var flashLightStatus: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        openFlashLight()

        val handler = Handler(Looper.getMainLooper())
        
        // Define a function to toggle the flashlight and post it to the handler
        val toggleFlashLight = Runnable {
            if (flashLightStatus) {
                closeFlashLight()
            } else {
                openFlashLight()
            }
            // Post the same function again after a 5-second delay
            handler.postDelayed(this, 5000)
        }

        // Start the flashlight toggle loop
        handler.postDelayed(toggleFlashLight, 5000)
    }

    private fun openFlashLight() {
        val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        if (!flashLightStatus) {
            try {
                cameraManager.setTorchMode(cameraId, true)
                flashLightStatus = true
            } catch (e: CameraAccessException) {
            }
        }
    }

    private fun closeFlashLight() {
        val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        if (flashLightStatus) {
            try {
                cameraManager.setTorchMode(cameraId, false)
                flashLightStatus = false
            } catch (e: CameraAccessException) {
            }
        }
    }
}

这段代码将无限循环地在打开和关闭手电筒之间切换,每次等待5秒。

英文:
package com.example.flashlight

import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    var flashLightStatus: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        openFlashLight()

        while (true) {
            Handler(Looper.getMainLooper()).postDelayed({
                //Do something after 100ms
                closeFlashLight()
            }, 5000)
            Handler(Looper.getMainLooper()).postDelayed({
                //Do something after 100ms
                openFlashLight()
            }, 5000)
        }
    }

    private fun openFlashLight() {
        val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        if (!flashLightStatus) {
            try {
                cameraManager.setTorchMode(cameraId, true)
                flashLightStatus = true

            } catch (e: CameraAccessException) {
            }
        } else {
            try {
                cameraManager.setTorchMode(cameraId, false)
                flashLightStatus = false
            } catch (e: CameraAccessException) {
            }
        }
    }

    private fun closeFlashLight()
    {
        val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        if (flashLightStatus) {
            try {
                cameraManager.setTorchMode(cameraId, false)
                flashLightStatus = false

            } catch (e: CameraAccessException) {
            }
        } else {
            try {
                cameraManager.setTorchMode(cameraId, true)
                flashLightStatus = true
            } catch (e: CameraAccessException) {
            }
        }
    }
}

This now just open the flashlight on the phone and the flashlight stay open all the time because the while(true)

while (true) {
            Handler(Looper.getMainLooper()).postDelayed({
                //Do something after 100ms
                closeFlashLight()
            }, 5000)
            Handler(Looper.getMainLooper()).postDelayed({
                //Do something after 100ms
                openFlashLight()
            }, 5000)
        }

but if I'm removing the while true and doing only:

openFlashLight()
        Handler(Looper.getMainLooper()).postDelayed({
            //Do something after 100ms
            closeFlashLight()
        }, 5000)

This will open the flashlight and will wait 5 seconds then will close the flashlight.
But I want to make something endless that it will open the flash light wait 5 seconds close the flashlight wait 5 seconds open the flashlight wait 5 seconds close.

That way nonstop. Open/close each 5 seconds nonstop. That's why I tried to use the while(true) but then the flashlight just keep staying open nonstop.

答案1

得分: 1

如果您想每隔5秒重复执行手电筒的开关循环,可以像这样做:

  1. 将一个布尔标志作为类成员:
var flashLightOn = false
  1. 创建一个启动手电筒的方法:
fun startFlashLight() {
    openFlashlight()
    flashLightOn = true

    val handler = Handler(Looper.getMainLooper())
    handler.postDelayed(object : Runnable() {
        override fun run() {
            if (flashLightOn) {
                closeFlashLight()
            } else {
                openFlashlight()
            }

            // 更改开关状态并在5秒后再次调用相同的Runnable
            flashLightOn = !flashLightOn
            handler.postDelayed(this, 5000)
        }
    }, 5000)
}
  1. 要停止这个处理程序,请调用:handler.removeCallbacksAndMessages(null)
英文:

If you want to repeat the flashlight on/off cycles every 5 seconds you can do something like this:

  1. Keep a boolean flag as a class member:
var flashLightOn = false
  1. Make a method that start the flashlight
fun startFlashLight() {
    openFlashlight()
    flashLightOn = true

    val handler = Handler(Looper.getMainLooper())
    handler.postDelayed(object: Runnable() {
        override fun run() {
            if (flashLightOn) {
                closeFlashLight()
            } else {
                openFlashlight()
            }
            
            // Changing the toggle and calling the same Runnable again after 5 seconds
            flashLightOn = !flashLightOn
            handler.postDelayed(this, 5000)
        }
    }, 5000)
}

  1. To stop this handler call: handler.removeCallbacksAndMessages(null)

答案2

得分: -1

You can achieve this by using kotlin coroutines:

val scope = CoroutineScope(Dispatchers.Main)

scope.launch {
    while (true) {
        openFlashlight()
        delay(5000)
        closeFlashlight()
        delay(5000)
    }
}
runBlocking {
    delay(Long.MAX_VALUE)
}

And also add this dependency in the build.gradle module level file:

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")

And if you want to do it using a handler, you can try this code:

val handler = Handler(Looper.getMainLooper())
var isFlashlightOpen = false

val toggleFlashlight = object : Runnable {
    override fun run() {
        if (isFlashlightOpen) {
            closeFlashlight()
            isFlashlightOpen = false
        } else {
            openFlashlight()
            isFlashlightOpen = true
        }
        handler.postDelayed(this, 5000)
    }
}

handler.postDelayed(toggleFlashlight, 5000)
英文:

You can achieve this by using kotlin coroutines

  val scope = CoroutineScope(Dispatchers.Main)

    scope.launch {
        while (true) {
            openFlashlight()
            delay(5000)
            closeFlashlight()
            delay(5000)
        }
    }
    runBlocking {
        delay(Long.MAX_VALUE)
    }

and also add this dependency in the build.gradle module level file

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")

And if you want to do it using handler you can try this I am not sure if this will work or not.

val handler = Handler(Looper.getMainLooper())
var isFlashlightOpen = false

val toggleFlashlight = object : Runnable {
    override fun run() {
        if (isFlashlightOpen) {
            closeFlashlight()
            isFlashlightOpen = false
        } else {
            openFlashlight()
            isFlashlightOpen = true
        }
        handler.postDelayed(this, 5000)
    }
}

handler.postDelayed(toggleFlashlight, 5000)

huangapple
  • 本文由 发表于 2023年5月21日 22:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定