如何从房间数据库或Android后台服务中的活动意图中连续获取数据

时间:2019-04-08 19:24:00

标签: android kotlin android-service

我通过在其中传递值的意图来调用我的服务类,我想在屏幕上显示这些文本(需要获得屏幕上方的显示权限),甚至在应用程序关闭时也是如此。但是,它在应用程序处于活动状态时仍然有效,但是当我关闭应用程序时,onStartCommand(intent: Intent?, flags: Int, startId: Int)方法以空的intent值再次运行,这就是我丢失从intent中获取的数据的问题。当onStartCommand首先在应用程序上运行时,我尝试在sharedPreference中传递这些值,然后,如果应用程序关闭,我将无法从sharedPreference获取数据。如何从room databasesharedPreferenceintent的后台服务中获取数据,这是最佳实践?

class PopupService: Service() {
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

//Initializing value 
    var interval:Long = 500
    val mTimer = Timer()
    lateinit var pref: SharedPreferences
    lateinit var wm:WindowManager
    lateinit var textView:TextView
    lateinit var data:ArrayList<String>


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        Log.d("MyNameisNotName","Started")

        //I am getting arrayList and storing to data. 
        if(intent!= null)
        data = intent.getStringArrayListExtra("messages")

      //Initializing values to popup texts on screen
        wm = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val inflater: LayoutInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        textView = inflater.inflate(R.layout.messages, null) as TextView
        val data = App.getDb
        mTimer.scheduleAtFixedRate(TimeDisplayTimerTask(wm,textView,data), 0, interval)

        return super.onStartCommand(intent, flags, startId)
    }


//Function to handle action periodiaclly in given duration
    class TimeDisplayTimerTask(val wm: WindowManager,val textView: TextView,val db:AppDb) : TimerTask() {

        var params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT)


        val handler = Handler()

        fun textDecoration(textView: TextView,data:List<Memo>) {
            try {
                textView.text = data[Random.nextInt(data.size-1)].text
                textView.textSize = 45f
                textView.setBackgroundColor(Color.WHITE)
                textView.setTextColor(Color.BLUE)
                textView.setPadding(10, 10, 10, 10)
            }catch (e:Exception){

            }
        }

        override fun run() {

         val myRun = Runnable{
                val displaymetrics = DisplayMetrics()

                wm.defaultDisplay.getMetrics(displaymetrics)
                val width = displaymetrics.widthPixels
                val height = displaymetrics.heightPixels

                params.x = Random.nextInt(width - 10)
                params.y = Random.nextInt(height - 10)
                var data = db.getMemoDao.getAll().value

                    Log.d("MyNameisNotName","Hi there"+data?.size.toString())
                    if(data!=null)
                textDecoration(textView,data)


                if (textView.isShown)
                    wm.removeView(textView)

                wm.addView(textView, params)
            }

                handler.post(myRun)
        }

        override fun cancel(): Boolean {
            if(textView.isShown)
                wm.removeView(textView)
            return super.cancel()
        }

    }



    override fun onDestroy() {
        super.onDestroy()
        if(textView.isShown)
            wm.removeView(textView)
        try{
            mTimer.cancel()
        }catch (e:Exception){

        }
        Log.d("MyNameisNotName","Destroyed")

    }
} ```

1 个答案:

答案 0 :(得分:0)

当您在Android 8.0及更高版本上运行您的应用程序时,您的服务可能会被终止

如果符合条件(非常有用并显示通知),则可以尝试在前景中运行服务,因此不应将其终止。

您可以在此处阅读有关作为前台服务启动服务的更多信息:

https://developer.android.com/guide/components/services#Foreground

或者如果您保留服务实现(不建议使用),则可以尝试返回Service。在onStartCommand()中返回START_REDELIVER_INTENT,这将重新传递原始的Intent