通过Android后台服务Kotlin轮询在线打印机队列

问题描述 投票:1回答:1

我在尝试轮询在线托管的打印队列时遇到问题

基本上,打印队列的要点是,当您调用url地址时,如果队列中有一个项目,它将返回该项目;如果没有,则不返回任何内容,即超时每次调用时,打印队列将清空1

-已删除-

**编辑**测试此代码是否在应用程序处于打开状态且在后台运行时有效,但在应用程序关闭时无效。理想情况下,我想覆盖一下

替代解决方案,欢迎使用,这是我的代码:

打印机服务

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        mRunning = true
        Thread{
            while(mRunning){
                Thread.sleep(30000)
                val response = transmit
                    .sendRequestManual("printerURL")
                if (response != null){
                    val openData = response.getElementsByTagName("printdata")
                    if(openData.length > 0){
                        for (socket in sockets) {
                            /* Bluetooth Printers */
                            write(openData.item(0).textContent, socket)
                        }
                    }
                }
            }
        }.start()
        return START_STICKY
    }

如果服务被销毁,其中mRunning设置为false

发送

fun sendRequestManual(sendURL: String): Document?{
        /* create the XML form to be sent */
        val client = OkHttpClient()
        val blockingQueue: BlockingQueue<Document> = ArrayBlockingQueue(1)


        val request = Request.Builder()
            .url(sendURL)
            .get()
            .build()

        client.newCall(request).enqueue(object: Callback{
            override fun onFailure(call: Call, e: IOException){
                /* onFailure is called each time */
            }

            override fun onResponse(call: Call, response: Response) {
                if(!response.isSuccessful){

                } else {
                    responseXML = response.body?.string()
                    blockingQueue.add(parseStringXMLDoc(responseXML!!))
                }
            }
        })
        return blockingQueue.poll(10,TimeUnit.SECONDS)
    }

清单

       <service
            android:name=".services.PrintService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"/>
android kotlin android-service okhttp polling
1个回答
0
投票

我的代码未正确轮询,仍然在应用关闭时寻求答案以进行轮询

已删除

Thread.sleep(30000)

将阻塞队列时间增加到90秒

return blockingQueue.poll(90,TimeUnit.SECONDS)
© www.soinside.com 2019 - 2024. All rights reserved.