Создала мелкий Service который по таймеру должен выдергивать инфу с сайта, инфа дергается все норм,
но проблема с работой при неактивном экране телефона (заблокированном), иногда ооочень в редких случах вроде как срабатывает,
но в основном тишина, как только начинаешь пользоваться телефоном то Service просыпается сам и начинает работать как надо... как его заставить работать при блокированном экране.... все разрешения/уведомления выставила по максимуму, даже контроль фоновой активности установила на - "Нет ограничений"
Android 9
MainActivity
Код: Выделить всё
package ru.ookamilb.musa
import ...
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
//------------------------------------------------------------------------ id
enum class Ids(val sClass: String) {
FRTS("td[class=pid-104396-last]"),
Brent("td[class=lastNum pid-8833-last]");
fun get() = sClass
}
//------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.requestWindowFeature(Window.FEATURE_NO_TITLE)
supportActionBar?.hide()
setContentView(R.layout.activity_main)
}
@RequiresApi(Build.VERSION_CODES.O)
fun onStart(view: View){
if (btnStart.text == "Старт") {
btnStart.text = "Стоп"
btnStart.setTextColor(Color.RED)
startService(Intent(this, ServiceMusa::class.java))
} else {
btnStart.text = "Старт"
btnStart.setTextColor(Color.BLACK)
stopService(Intent(this, ServiceMusa::class.java))
}
}
}
Код: Выделить всё
package ru.ookamilb.musa
import ...
class ServiceMusa : Service() {
private lateinit var mPlayer: MediaPlayer
private val periodzaprosa: Long = 60 // сек
private var idNotif = 1
lateinit var notiman: NotificationManager
lateinit var notichann: NotificationChannel
lateinit var builder: NotificationCompat.Builder
var znacheniya = arrayOf(0.00f, 0.00f)
var s_neft = ""
var s_rts = ""
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
notiman = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // менеджер уведомлений
mPlayer = MediaPlayer.create(this, R.raw.hour)
mPlayer.isLooping = false
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
runTask()
return START_REDELIVER_INTENT // Здесь пробовала разные варианты, ничего не сработало, решила оставить это
}
override fun onDestroy() {
stopTask()
super.onDestroy()
}
//-------------------------------------------------------------------------------------------------------------------------Создание уведомления
fun uved() {
val options: BitmapFactory.Options = BitmapFactory.Options() // картинка в Уведомлении
val bitmap : Bitmap = BitmapFactory.decodeResource(resources, R.drawable.gravik, options)
val intent = Intent(this, MainActivity::class.java)
val idchannel = "idmusachannel"
val descchannel = "ru.ookamilb.musa"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notichann = NotificationChannel(idchannel, descchannel, NotificationManager.IMPORTANCE_HIGH)
notichann.enableLights(true)
notichann.lightColor = Color.RED
notichann.enableVibration(true)
builder = NotificationCompat.Builder(this, idchannel)
.setContentTitle(Calendar.getInstance().time.toString())
.setContentText("RTS - " + s_rts + " | Нефть Brent - " + s_neft)
.setSmallIcon(R.drawable.notification_icon_background)
.setLargeIcon(bitmap)
notiman.createNotificationChannel(notichann)
} else {
builder = NotificationCompat.Builder(this)
.setContentTitle(Calendar.getInstance().time.toString())
.setContentText("RTS - " + s_rts + " | Нефть Brent - " + s_neft)
.setSmallIcon(R.drawable.notification_icon_background)
.setLargeIcon(bitmap)
}
notiman.notify(idNotif++, builder.build())
}
//-------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------Поток
inner class Potok1(): AsyncTask<Unit, Unit, String>() {
private var online: String = "off"
var s_neft = ""
var s_rts = ""
override fun doInBackground(vararg params: Unit?): String? {
try {
val js: Document = Jsoup.connect("https://ru.investing.com/indices/indices-futures").get() // Дергаем сайт
var jcont = js.select(MainActivity.Ids.Brent.get()) // Контент...
s_neft = jcont.eq(0).text().replace(',','.')
jcont = js.select(MainActivity.Ids.FRTS.get())
s_rts = jcont.eq(0).text().replace(',','.')
online = "on"
return "Good"
} catch (e: IOException) {
online = "off"
return "No good"
}
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
if (online == "on") {
znacheniya[0] = s_neft.toFloat()
if (znacheniya[1] == 0.0f) {
znacheniya[1] = s_neft.toFloat()
} else if (Math.abs(znacheniya[0] - znacheniya[1]) >= 0.05) {
znacheniya[1] = znacheniya[0]
uved()
}
}
}
}
//--------------------------------------------------------------------------------------------------------------------- Таймер на каждую минуту
fun runTask(){
Timer("timer111",false).schedule(0,(periodzaprosa * 1000),
{
mPlayer.start()
val potok = Potok1(); potok.execute()
}
)
}
//------------------------------------------------------------------------------------------------------------------------- Стоп таймер
fun stopTask(){
Timer("timer111",false).cancel()
}
}