AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MovementDetectionService"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
MainActivity.kt
package com.example.myapplication
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, MovementDetectionService::class.java))
} else {
startService(Intent(this, MovementDetectionService::class.java))
}
}
}
MovementDetectionService.kt
package com.example.myapplication
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Vibrator
import android.widget.Toast
import androidx.core.app.NotificationCompat
class MovementDetectionService : Service(), SensorEventListener {
private lateinit var sensorManager: SensorManager
private lateinit var accelerometer: Sensor
private var lastX: Float = 0f
private var lastY: Float = 0f
private var lastZ: Float = 0f
private var lastTime: Long = 0L
private val threshold = 0.2f // Ajustar este valor según sea necesario
private val delay = 7000L // Cambiado a 10 segundos
private var handler: Handler? = null
private lateinit var runnable: Runnable
private val NOTIFICATION_CHANNEL_ID = "MovementDetectionChannel"
private val NOTIFICATION_ID = 101
override fun onCreate() {
super.onCreate()
Toast.makeText(this, "funcionando", Toast.LENGTH_SHORT).show()
createNotificationChannel()
val notification = createNotification()
startForeground(NOTIFICATION_ID, notification)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!!
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)
handler = Handler()
runnable = Runnable {
// Activar alarma cuando el teléfono esté inactivo después del retraso
triggerAlarm()
}
}
override fun onDestroy() {
super.onDestroy()
sensorManager.unregisterListener(this)
handler?.removeCallbacks(runnable)
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
override fun onSensorChanged(event: SensorEvent?) {
event?.let {
if (it.sensor.type == Sensor.TYPE_ACCELEROMETER) {
val currentTime = System.currentTimeMillis()
if (currentTime - lastTime > delay) {
lastTime = currentTime
val x = it.values[0]
val y = it.values[1]
val z = it.values[2]
val deltaX = Math.abs(x - lastX)
val deltaY = Math.abs(y - lastY)
val deltaZ = Math.abs(z - lastZ)
if (deltaX < threshold && deltaY < threshold && deltaZ < threshold) {
handler?.postDelayed(runnable, delay)
} else {
handler?.removeCallbacks(runnable)
}
lastX = x
lastY = y
lastZ = z
}
}
}
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Movement Detection Service",
NotificationManager.IMPORTANCE_DEFAULT
)
channel.description = "Channel description"
channel.enableLights(true)
channel.lightColor = Color.RED
notificationManager.createNotificationChannel(channel)
}
}
private fun createNotification(): Notification {
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Movement Detection Service")
.setContentText("Service running")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build()
}
private fun triggerAlarm() {
Toast.makeText(this, "alarma", Toast.LENGTH_SHORT).show()
// Activar una alarma o cualquier otra acción aquí
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(1000) // Vibrar durante 1 segundo
// Se puede reproducir un sonido, mostrar una notificación, etc., para alertar al usuario
}
} Publicado el día 8 de diciembre de 2023 CATEGORÍAS Android , Kotlin , Lo mejor