Need help, I'm making a screen locker app using React Native, and want to get an event when the android power button is pressed...
Thanks in advance..
CodePudding user response:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
// 1. onKeyDown is a boolean function, which returns the state of
//the KeyEvent.
// 2. This function is an internal function, that functions outside
//the actual application.
// 3. When any Key is pressed, a Toast appears with the following
//message.
// 4. This code can check if the device responds to any Key.
//override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_VOLUME_DOWN ->
Toast.makeText(applicationContext, "Volume Down Key Pressed",
Toast.LENGTH_SHORT).show()
KeyEvent.KEYCODE_VOLUME_UP ->
Toast.makeText(applicationContext,
"Volume Up Key Pressed", Toast.LENGTH_SHORT).show()
KeyEvent.KEYCODE_POWER -> Toast.makeText(applicationContext,
"Power Key Pressed", Toast.LENGTH_SHORT).show()
}
return true
}
}
CodePudding user response:
*You cannot override the power button press from your application. But when you press power button the screen turns on/off. So you can detect this using a broadcast receiver.
<receiver android:name=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
MyBroadCastReciever.java
public class MyBroadCastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//Take count of the screen off position
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//Take count of the screen on position
}
}
}
Hope this is helpful for you.
Note:-For to keep my broadcast receiver always running in Background.I am written one Background Service which continuously start in background and give boost to my broadcast receiver.*
CodePudding user response:
You can use the react-native-keyevent package for react native.
componentDidMount() {
KeyEvent.onKeyDownListener((keyEvent) => {
if (keyEvent.keyCode === 'Keycode of the power button'){
this.timeout = setTimeout(() => {
//Your SOS Function here
}, 1000)
}
});
KeyEvent.onKeyUpListener((keyEvent) => {
if (keyEvent.keyCode === 'Keycode of the power button'){
clearTimeout(this.timeout)
}
})
}
componentWillUnmount() {
KeyEvent.removeKeyDownListener();
KeyEvent.removeKeyUpListener();
}