Проблема приведения объекта Service Binder при подключении службы - PullRequest
0 голосов
/ 04 марта 2020

У меня проблема с подключением к услуге в этой строке var binder:TwentyFourHoursService.LocalBinder = service as TwentyFourHoursService.LocalBinder, и я не смог найти решение за последние два дня

 override fun onServiceConnected(
            className: ComponentName,
            service: IBinder
        ) { // cast the IBinder and get MyService instance
            var binder:TwentyFourHoursService.LocalBinder = service as TwentyFourHoursService.LocalBinder
            myService = binder.getService()
            bound = true
             // serviceCallbacks =this as ServiceCallbacks
            myService!!.setCallbacks(mActivity) // register
        }

Вот мой сервис

class TwentyFourHoursService : Service() {
    private val mHandler: Handler = Handler() //run on another Thread to avoid crash
    private var mTimer: Timer? = null //timer handling

    // Binder given to clients
    private val binder: IBinder = LocalBinder()


    override fun onBind(intent: Intent): IBinder {
//        throw UnsupportedOperationException("Not yet implemented")
        return binder
    }

    override fun onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer!!.cancel() else mTimer = Timer() //recreate new
        mTimer!!.scheduleAtFixedRate(
            TimeDisplay(),
            0,
            notify
        ) //Schedule task

        //Timer().scheduleAtFixedRate(TimeDisplay(),0, notify)
    }
    fun setCallbacks(callbacks: ServiceCallbacks?) {
        serviceCallbacks = callbacks
    }

    override fun onDestroy() {
        super.onDestroy()
        mTimer!!.cancel() //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show()
    }

    //class TimeDisplay for handling task
    internal inner class TimeDisplay : TimerTask() {
        override fun run() { // run on another thread
            mHandler.post(Runnable {
                // display toast
               /* if (serviceCallbacks!=null) {
                    serviceCallbacks!!.doSomething()
                }*/
                // Reload current fragment
                // Reload current fragment

//                startActivity(Intent(applicationContext, FitnessSlideMenuScreen::class.java))
//                rFitnessSlideMenuScreen().displaySelectedFragment(HomeFragment())
                Toast.makeText(applicationContext, "Service is running", Toast.LENGTH_SHORT).show()
            })
        }
    }

ОШИБКА

***java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.example.beyahfitness.service.TwentyFourHoursService$LocalBinder***
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...