android#service的基本使用

service 的实例代码

package com.lyr.myapplication.service


import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ExampleService : LifecycleService() {
    var number = 0
    override fun onCreate() {
        super.onCreate()

        Log.i("xxx", "开启服务")
    }

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

        lifecycleScope.launch{
            while (true) {
                delay(1_000)
                Log.d("xx","${++number}")
            }
        }


        return super.onStartCommand(intent, flags, startId)
 

    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)
        TODO("XX ")
    }
}

onCreate 的时候,启动后台服务



package com.lyr.myapplication

import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.lyr.myapplication.service.ExampleService
import kotlinx.android.synthetic.main.webview_example.*

/**
 * @Author  lyr
 * @create 2020/10/12 22:18
 */
class WebViewExampleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)

        setContentView(R.layout.webview_example)
        Log.i("x","加载页面")
        webView.settings.javaScriptEnabled = true
//        webView.loadUrl("https://m.baidu.com")
        //webView.loadUrl("file:///")

        webView.loadUrl("file:///android_asset/example.html");
//        Intent(this,ExampleActivity::class.java).also {
//            startActivity(it)
//        }
        Intent(this,ExampleService::class.java).also {
            startService(it)
        }
    }
}

需要导入 的 依赖



    implementation group: 'androidx.lifecycle', name: 'lifecycle-service', version: '2.2.0'
    // https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-livedata
    implementation group: 'androidx.lifecycle', name: 'lifecycle-livedata', version: '2.2.0'
    // https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-livedata-ktx
    implementation group: 'androidx.lifecycle', name: 'lifecycle-livedata-ktx', version: '2.2.0'
    // https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-runtime
    implementation group: 'androidx.lifecycle', name: 'lifecycle-runtime-ktx', version: '2.2.0'


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值