Android Service+协程的简单用法

Service+协程

  • 导入
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'//lifecycleScope
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'//viewModelScope
  • 启动协程
    job = GlobalScope.launch

  • 停止协程
    job?.cancel()

  • Android 8.0 以上不推荐使用IntentService了,Google推荐使用JobIntentService

    • 由于线程的不好控制,可以使用协程来代替
    • 协程中的任务完成后,停止Service
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate: ")
        job = GlobalScope.launch {
            repeat(20) {
                Log.d(TAG, "onStartCommand: $it")
                simpleBinder.onListener.invoke(it)
                delay(1000)
            }
        }
    }
  • MyService中的完整代码
class MyService : Service() {

    companion object {

        private const val TAG = "MyService"

        var starter: Intent? = null

        fun start(context: Context) {
            if (starter == null){
                starter = Intent(context, MyService::class.java)
            }
            context.startService(starter)
        }

        fun stop(context: Context) {
            starter?.let {
                context.stopService(starter)
            }
        }
    }


    var job: Job? = null
    
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate: ")
        job = GlobalScope.launch {
            repeat(10) {
                Log.d(TAG, "onStartCommand: $it")
                delay(1000)
            }
            stop(this@MyService)
            //或者使用stopSelf()
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        TODO("Not yet implemented")
    }

    override fun onDestroy() {
        super.onDestroy()
        //停止协程
        job?.cancel()
        Log.d(TAG, "onDestroy: ")
    }

}
  • 可以看出在stopService后,协程也停止了
 D/MyService: onStartCommand: 0
 D/MyService: onStartCommand: 1
 D/MyService: onStartCommand: 2
 D/MyService: onStartCommand: 3
 D/MyService: onStartCommand: 4
 D/MyService: onDestroy: 
  • 另外任务完成后,服务销毁
2021-04-06 16:20:00.183 4859-5016/com.vision.mycoroutineservice D/MyService: onStartCommand: 2
2021-04-06 16:20:01.185 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 3
2021-04-06 16:20:02.188 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 4
2021-04-06 16:20:03.192 4859-5015/com.vision.mycoroutineservice D/MyService: onStartCommand: 5
2021-04-06 16:20:04.197 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 6
2021-04-06 16:20:05.200 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 7
2021-04-06 16:20:06.203 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 8
2021-04-06 16:20:07.205 4859-5015/com.vision.mycoroutineservice D/MyService: onStartCommand: 9
2021-04-06 16:20:08.219 4859-4859/com.vision.mycoroutineservice D/MyService: onDestroy: 

GlobalScope

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,我很愿意回答您的问题。下面是一个 Kotlin + 协程 + Retrofit + MVVM 实现网络请求的示例: 1. 在 build.gradle 中添加以下依赖: ``` implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0' implementation 'com.squareup.retrofit2:retrofit:2.8.1' implementation 'com.squareup.retrofit2:converter-gson:2.8.1' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' ``` 2. 创建 Retrofit 接口: ```kotlin interface ApiService { @GET("users/{user}/repos") suspend fun getRepos(@Path("user") user: String): List<Repo> } ``` 3. 创建数据模型: ```kotlin data class Repo(val name: String) ``` 4. 创建 Repository: ```kotlin class MainRepository(private val apiService: ApiService) { suspend fun getRepos(user: String): List<Repo> { return apiService.getRepos(user) } } ``` 5. 创建 ViewModel: ```kotlin class MainViewModel(private val repository: MainRepository) : ViewModel() { private val _repos = MutableLiveData<List<Repo>>() val repos: LiveData<List<Repo>> = _repos fun getRepos(user: String) { viewModelScope.launch { _repos.value = repository.getRepos(user) } } } ``` 6. 创建 Activity/Fragment: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val apiService = Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiService::class.java) val repository = MainRepository(apiService) viewModel = ViewModelProvider(this, MainViewModelFactory(repository))[MainViewModel::class.java] viewModel.repos.observe(this, Observer { repos -> // do something with repos }) viewModel.getRepos("octocat") } } ``` 以上就是一个使用 Kotlin + 协程 + Retrofit + MVVM 实现网络请求的示例。希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值