#android
#Android
Вопрос:
Вот я попытался настроить ActivityRecognitionClient
получение действий, но обновлений нет… (Проверено на Android 10 и 11)
class ActivitiesChecker(private val context: Context) {
private val activityRecognitionClient = ActivityRecognitionClient(context)
private val pendingIntent = PendingIntent.getService(
context,
1,
Intent(context, DetectedActivitiesIntentService::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val type = intent.getIntExtra(DetectedActivitiesIntentService.TYPE, -1)
val confidence = intent.getIntExtra(DetectedActivitiesIntentService.TYPE, 0)
ToastUtil.toastLong(context, "$type, $confidence")
}
}
fun start() {
LocalBroadcastManager.getInstance(context).registerReceiver(
broadcastReceiver,
IntentFilter(DetectedActivitiesIntentService.TAG)
)
val task = activityRecognitionClient.requestActivityUpdates(1000L, pendingIntent)
task.addOnSuccessListener {
ToastUtil.toastLong(context, "Successfully requested activity updates")
}
task.addOnFailureListener {
ToastUtil.toastLong(context, "Failed requesting activity updates")
}
}
fun stop() {
LocalBroadcastManager.getInstance(context).unregisterReceiver(broadcastReceiver)
val task = activityRecognitionClient.removeActivityUpdates(pendingIntent)
task.addOnSuccessListener {
//
}
task.addOnFailureListener {
//
}
}
}
Обслуживание
class DetectedActivitiesIntentService : JobIntentService() {
override fun onHandleWork(intent: Intent) {
val result = ActivityRecognitionResult.extractResult(intent) ?: return
val activity = result.mostProbableActivity
Log.i(TAG, "${activity.type} ${activity.confidence}")
broadcastActivity(activity)
}
private fun broadcastActivity(activity: DetectedActivity) {
val intent = Intent(TAG).apply {
putExtra(TYPE, activity.type)
putExtra(CONFIDENCE, activity.confidence)
}
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
companion object {
val TAG = "${DetectedActivitiesIntentService::class.java.name}.DetectedActivitiesIntentService"
const val TYPE = "type"
const val CONFIDENCE = "confidence"
}
}
Он печатает Successfully requested activity updates
так, что все должно работать, но обновлений по-прежнему нет
Добавлены разрешения
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
и ACTIVITY_RECOGNITION
был запрошен во время выполнения (должен быть запрошен на Android 29 )