如何始终运行应用程序Android Kotlin并在锁定屏幕上每1分钟发送一次请求

问题描述

请帮助我 我想在后台运行应用程序,每隔1分钟将请求发送到服务器,并且应用程序永远不会挂起 我尝试使用前台服务和后台服务,我的应用程序在锁定屏幕上挂起。 锁定屏幕应用程序之后运行的应用程序可以继续运行15-30分钟,并在解锁屏幕应用程序继续运行时进入暂停模式 (在设备上运行:Android 5.1,Android 7.1.1和Android 9)

我的代码:MainActivity

package com.example.releepreadjson

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolBox.JsonObjectRequest
import com.android.volley.toolBox.StringRequest
import com.android.volley.toolBox.Volley
import org.json.JSONObject
import java.io.File

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        val PERMISSION_ALL = 1
        val PERMISSIONS_LIST = arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WAKE_LOCK
        )
        if (!hasPermissions(this,*PERMISSIONS_LIST)) {
            ActivityCompat.requestPermissions(this,PERMISSIONS_LIST,PERMISSION_ALL)
        }

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        InitializeReadJson()
    }

    fun InitializeReadJson(){
        ReadJsonInForeground.startService(this,"ReadJson Service is running...")
        val wakeLock: PowerManager.WakeLock =
            (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
                newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"ReadJsonInForeground::lock").apply {
                    acquire(60*60*24*1000L /*10 minutes*/)
                }
            }
    }

    fun hasPermissions(context: Context,vararg permissions: String): Boolean = permissions.all {
        ActivityCompat.checkSelfPermission(context,it) == PackageManager.PERMISSION_GRANTED
    }


}

我的代码:ReadJsonInForeground>服务

package com.example.releepreadjson

import android.app.NotificationChannel
import android.app.notificationmanager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.*
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolBox.JsonObjectRequest
import com.android.volley.toolBox.Volley
import org.json.JSONObject
import java.io.File

class ReadJsonInForeground : Service() {

    private val CHANNEL_ID = "ReadJsonServiceKotlin"
    private var ListIncomingFile = ArrayList<String>()
    var index = 0

    companion object {

        fun startService(context: Context,message: String) {
            val startIntent = Intent(context,ReadJsonInForeground::class.java)
            startIntent.putExtra("inputExtra",message)
            ContextCompat.startForegroundService(context,startIntent)

        }

        fun stopService(context: Context) {
            val stopIntent = Intent(context,ReadJsonInForeground::class.java)
            context.stopService(stopIntent)
        }
    }

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

        val mainHandler = Handler(Looper.getMainLooper())

        mainHandler.post(object : Runnable {
            override fun run() {
                println("Running :$index")
                index += 1
                sendDataRequestNoData()
                mainHandler.postDelayed(this,78000)
            }
        })

        //do heavy work on a background thread
        val input = intent?.getStringExtra("inputExtra")
        createNotificationChannel()
        val notificationIntent = Intent(this,MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,notificationIntent,0
        )

        val notification = NotificationCompat.Builder(this,CHANNEL_ID)
            .setContentTitle("ReadJson Service Kotlin Example")
            .setContentText("ReadJson")
            .setContentText("Send Request")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .build()

        startForeground(1,notification)
        //stopSelf();
        return START_NOT_STICKY
    }

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

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(CHANNEL_ID,"ReadJson Service Channel",notificationmanager.IMPORTANCE_DEFAULT)

            val manager = getSystemService(notificationmanager::class.java)
            manager!!.createNotificationChannel(serviceChannel)
        }
    }

    private fun sendDataRequestNoData() {
         val url = "http://127.0.0.1/TestAPI/save_log_request.PHP"


        // Post parameters
        // Form fields and values
        val params = HashMap<String,String>()
        params["device_id"] = "THOR5Pro"
        params["device_values"] = "No Data"
        val jsonObject = JSONObject(params as Map<*,*>)

        println(jsonObject)
        // Volley post request with parameters
        val request = JsonObjectRequest(Request.Method.POST,url,jsonObject,Response.Listener { response ->
                // Process the json
                try {
                    println("Response: $response")
                } catch (e: Exception) {
                    println("Exception: $e")
                }

            },Response.ErrorListener {
                // Error in request
                println("Volley error: $it")
            })


        // Volley request policy,only one time request to avoid duplicate transaction
        request.retryPolicy = DefaultRetryPolicy(
            DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,// 0 means no retry
            0,// DefaultRetryPolicy.DEFAULT_MAX_RETRIES = 2
            1f // DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        )

        // Add the volley post request to the request queue
        Volley.newRequestQueue(this).add(request)

    }
}

请帮助我。对不起,我的英语不好。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...