您当前的位置: 首页 >  ide
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

ContentProvider妙用 --- 完成application初始化

沙漠一只雕得儿得儿 发布时间:2021-03-27 14:21:51 ,浏览量:0

我们都知道 ContentProvideronCreate() 的调用时机介于 ApplicationattachBaseContext()onCreate() 之间。

那么有些操作需要在application中初始化的工作我们完全可以放到ContentProvider中处理,leakCanary2.0就是这么做的,把 init 的逻辑放到库内部,让调用方完全不需要在 Application 里去进行初始化了,十分方便。这样下来既可以避免开发者忘记初始化导致一些错误,也可以让我们庞大的 Application 代码更加简洁。

在 leakcanary-leaksentry 模块的 AndroidManifest.xml文件中可以看到:




  
    
  

再经过查看 LeakSentryInstaller 可以看到:

package leakcanary.internal

import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import leakcanary.CanaryLog

/**
 * Content providers are loaded before the application class is created. [LeakSentryInstaller] is
 * used to install [leaksentry.LeakSentry] on application start.
 */
internal class LeakSentryInstaller : ContentProvider() {

  override fun onCreate(): Boolean {
    CanaryLog.logger = DefaultCanaryLog()
    val application = context!!.applicationContext as Application
    InternalLeakSentry.install(application)
    return true
  }

  override fun query(
    uri: Uri,
    strings: Array?,
    s: String?,
    strings1: Array?,
    s1: String?
  ): Cursor? {
    return null
  }

  override fun getType(uri: Uri): String? {
    return null
  }

  override fun insert(
    uri: Uri,
    contentValues: ContentValues?
  ): Uri? {
    return null
  }

  override fun delete(
    uri: Uri,
    s: String?,
    strings: Array?
  ): Int {
    return 0
  }

  override fun update(
    uri: Uri,
    contentValues: ContentValues?,
    s: String?,
    strings: Array?
  ): Int {
    return 0
  }
}

 

关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0353s