首页 > 解决方案 > 谷歌活动识别意图服务在某些设备上不起作用

问题描述

我对谷歌活动识别 API 有一个奇怪的问题,我的服务运行良好,并且在华为和三星制造的设备上检测到的活动非常好,但是当我在 2 Motos 和诺基亚上对其进行测试时,它没有工作。华为和诺基亚在 Android 9、第一个 Moto 8.1、第二个 Moto 10 和三星 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>

标签: javaandroidandroid-studiokotlin

解决方案


实际上,我的问题在于我如何调用我的服务,在声明广播者并使其在特定事件时触发它开始工作!


推荐阅读