lab10
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
|
||||
@@ -1,74 +1,101 @@
|
||||
package com.example.myapplication
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.widget.TextView
|
||||
import android.widget.Button
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
|
||||
class MainActivity : AppCompatActivity(), SensorEventListener {
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var sensorManager: SensorManager
|
||||
private var accelerometer: Sensor? = null
|
||||
private var lightSensor: Sensor? = null
|
||||
private val channelId = "lab10_channel"
|
||||
|
||||
private lateinit var tvAccelerometer: TextView
|
||||
private lateinit var tvLight: TextView
|
||||
// Лаунчер для запроса разрешений
|
||||
private val requestPermissionLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { isGranted: Boolean ->
|
||||
if (isGranted) {
|
||||
showNotification()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
tvAccelerometer = findViewById(R.id.tvAccelerometer)
|
||||
tvLight = findViewById(R.id.tvLight)
|
||||
createNotificationChannel()
|
||||
|
||||
// Получаем доступ к сенсорам
|
||||
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
|
||||
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
|
||||
|
||||
// Если сенсор отсутствует
|
||||
if (accelerometer == null) {
|
||||
tvAccelerometer.text = "Акселерометр не поддерживается"
|
||||
val btnNotify: Button = findViewById(R.id.btnNotify)
|
||||
btnNotify.setOnClickListener {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
// Проверяем разрешение
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
this,
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
showNotification()
|
||||
} else {
|
||||
// Запрашиваем разрешение
|
||||
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
if (lightSensor == null) {
|
||||
tvLight.text = "Датчик освещённости не поддерживается"
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
accelerometer?.also {
|
||||
sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)
|
||||
}
|
||||
lightSensor?.also {
|
||||
sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
sensorManager.unregisterListener(this)
|
||||
}
|
||||
|
||||
override fun onSensorChanged(event: SensorEvent?) {
|
||||
when (event?.sensor?.type) {
|
||||
Sensor.TYPE_ACCELEROMETER -> {
|
||||
val x = event.values[0]
|
||||
val y = event.values[1]
|
||||
val z = event.values[2]
|
||||
tvAccelerometer.text = "Акселерометр:\nX = %.2f\nY = %.2f\nZ = %.2f".format(x, y, z)
|
||||
}
|
||||
Sensor.TYPE_LIGHT -> {
|
||||
val lux = event.values[0]
|
||||
tvLight.text = "Освещённость: $lux люкс"
|
||||
} else {
|
||||
showNotification()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val name = "Lab10 Notifications"
|
||||
val descriptionText = "Канал для лабораторной работы 10"
|
||||
val importance = NotificationManager.IMPORTANCE_HIGH
|
||||
val channel = NotificationChannel(channelId, name, importance).apply {
|
||||
description = descriptionText
|
||||
}
|
||||
val notificationManager: NotificationManager =
|
||||
getSystemService(NotificationManager::class.java)
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showNotification() {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
this,
|
||||
android.Manifest.permission.POST_NOTIFICATIONS
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Интент для открытия MainActivity при клике
|
||||
val intent = Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this, 0, intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
val builder = NotificationCompat.Builder(this, channelId)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_info)
|
||||
.setContentTitle("Лабораторная работа 10")
|
||||
.setContentText("Это пример уведомления")
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
|
||||
with(NotificationManagerCompat.from(this)) {
|
||||
notify(1001, builder.build())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,9 @@
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tvAccelerometer"
|
||||
<Button
|
||||
android:id="@+id/btnNotify"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Акселерометр: данные отсутствуют" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tvLight"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Освещённость: данные отсутствуют" />
|
||||
android:text="Показать уведомление" />
|
||||
</LinearLayout>
|
||||
Reference in New Issue
Block a user