У меня странная проблема с API распознавания активности Google, мой сервис работает нормально и довольно хорошо обнаруживает действия на устройствах, изготовленных Huawei и Samsung, но когда я тестировал его на 2 Motos и Nokia, он не работал. Huawei и Nokia работают на Android 9, первый Moto 8.1, второй Moto 10 и Samsung Android 6/7
Вот мой сервис:
class DetectedActivitiesIntentService : IntentService("DetectedActivitiesIntentService"),
LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
private var mGoogleApiClient: GoogleApiClient? = null
private var monitoringIsNotStarted: Boolean = true
private var tempDistance = 0.0
private var maxSpeed = 0.0
override fun onCreate() {
mGoogleApiClient = GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
mGoogleApiClient!!.connect()
Toast.makeText(this, "Pracenje aktivnosti zapoceto", Toast.LENGTH_SHORT).show()
super.onCreate()
}
override fun onHandleIntent(intent: Intent?) {
if (monitoringIsNotStarted) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, DrivingMonitor::class.java))
println("FOREGROUND MONITOR ACTIVITY")
}else {
startService(Intent(this, DrivingMonitor::class.java))
println("BACKGROUND MONITOR ACTIVITY")
}
monitoringIsNotStarted = false
}
val detectedActivitiesIntent = Intent("activityChange")
detectedActivitiesIntent.putExtra("detectedActivities", ActivityRecognitionResult.extractResult(intent).probableActivities as ArrayList)
LocalBroadcastManager.getInstance(this).sendBroadcast(detectedActivitiesIntent)
val timeSt = currentTimeMillis()
var actionType = ActivityRecognitionResult.extractResult(intent).mostProbableActivity.type
if (actionType == ON_FOOT)
actionType = WALKING
val lastActionType = PreferenceManager.getDefaultSharedPreferences(this).getInt(KEY_LAST_DETECTED_TYPE, 3)
val lastTimestamp = PreferenceManager.getDefaultSharedPreferences(this).getLong(LAST_TIMESTAMP, 0)
val preferences = getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE)
val editor = preferences.edit()
if (actionType == lastActionType && trackedActivities.contains(actionType) && locations.size > 100) {
if (actionType != STILL) tempDistance = SphericalUtil.computeLength(locations.toMutableList())
var oldTempDistance = preferences.getFloat("tempDistance", 0.0f)
editor.putFloat("tempDistance", (tempDistance + oldTempDistance).toFloat())
editor.apply()
locations.clear()
}
if (actionType != lastActionType && trackedActivities.contains(actionType)) {
val preferencess = getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE)
val editorr = preferencess.edit()
val temp = preferencess.getFloat("tempDistance", 0.0f)
if (actionType == DetectedActivity.IN_VEHICLE)
driving(true)
var distance = SphericalUtil.computeLength(locations.toMutableList())
distance += temp
editorr.putFloat("tempDistance", 0.0f)
editorr.apply()
mGoogleApiClient?.disconnect()
locations.clear()
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putInt(KEY_LAST_DETECTED_TYPE, actionType)
.putLong(LAST_TIMESTAMP, timeSt)
.apply()
when (lastActionType) {
//TODO Remove hardcoded values for max and average speed
ON_BICYCLE -> {
if (!mGoogleApiClient!!.isConnected) mGoogleApiClient?.connect()
saveCyclingData(CyclingModel(lastTimestamp,timeSt,getAllUsers()[0],distance/1000,maxSpeed, 15.00))
}
RUNNING -> {
if (!mGoogleApiClient!!.isConnected) mGoogleApiClient?.connect()
saveRunningData(RunningModel(lastTimestamp,timeSt,getAllUsers()[0],distance/1000,maxSpeed.toLong(), 10))
}
WALKING -> {
if (!mGoogleApiClient!!.isConnected) mGoogleApiClient?.connect()
saveWalkingData(WalkingModel(lastTimestamp,timeSt,getAllUsers()[0],distance/1000))
driving(false)
// if(lastActionType == IN_VEHICLE) {
// rewardNotification(this)
// }
}
IN_VEHICLE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, SensorFusionService::class.java))
println("FOREGROUND MONITOR ACTIVITY")
}else {
startService(Intent(this, SensorFusionService::class.java))
println("BACKGROUND MONITOR ACTIVITY")
}
if (!mGoogleApiClient!!.isConnected) mGoogleApiClient?.connect()
saveDrivingData(DrivingModel(lastTimestamp,timeSt,getAllUsers()[0],distance/1000))
}
STILL -> {
saveStillData(StillModel(lastTimestamp, timeSt, getAllUsers()[0]))
Toast.makeText(this, "DETEKTOVAN STILL", Toast.LENGTH_LONG ).show()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(1, createNotification(this,actionType))
}else {
startRecognitionNotification(this, actionType)
}
}
}
fun driving(driving: Boolean) {
val intStart = Intent("QualityTracking")
intStart.putExtra("driving", driving)
sendBroadcast(intStart)
}
companion object {
val trackedActivities = listOf(ON_BICYCLE, RUNNING, WALKING, IN_VEHICLE, STILL, ON_FOOT)
var locations = arrayListOf<LatLng>()
}
override fun onLocationChanged(location: Location) {
if (location.accuracy < 100)
locations.add(LatLng(location.latitude, location.longitude))
if(location.hasSpeed()) {
val potentialMaxSpeed = location.speed
if (maxSpeed < potentialMaxSpeed)
maxSpeed = potentialMaxSpeed.toDouble()
}
}
private fun startLocationUpdates() {
val fastestInterval: Long = 1000
val updateInterval = defaultSharedPreferences.getString(Constants.LOCATION_UPDATE_INTERVAL, (10 * 1000).toString())
val precision = defaultSharedPreferences.getString(Constants.LOCATION_PRECISION, LocationRequest.PRIORITY_HIGH_ACCURACY.toString())
val mLocationRequest = LocationRequest.create()
.setPriority(precision!!.toInt())
.setInterval(updateInterval!!.toLong())
.setFastestInterval(fastestInterval)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
longToast("No permission to use gps")
return
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this)
// LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, LocationCallback(), Looper.getMainLooper())
}
override fun onConnectionSuspended(result: Int) {}
override fun onConnected(result: Bundle?) {
startLocationUpdates()
}
override fun onConnectionFailed(result: ConnectionResult) {}
}
Вот мой сервис заявлен в декларации
<receiver
android:name=".service.ServiceBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:process=":remote">
<intent-filter>
<action android:name="RestartService" />
</intent-filter>
</receiver>