简体   繁体   English

applicationContext.getSystemService(SmsManager::class.java) 在服务内返回 null

[英]applicationContext.getSystemService(SmsManager::class.java) returning null inside a Service

Viewed quite a few similar questions so far, but none ended up a solution.到目前为止查看了很多类似的问题,但没有一个最终解决。

I'm trying to start up a foreground service in order to handle SMS messaging.我正在尝试启动前台服务以处理 SMS 消息。 This service is started when the app is first opened and does work on background threads via kotlin coroutines.此服务在应用程序首次打开时启动,并通过 kotlin 协程在后台线程上工作。 This process remains active even when the app has been closed.即使应用程序已关闭,此过程仍处于活动状态。

I'm not too well versed on the various Contexts, but I would have thought applicationContext would exist for the lifetime of the app, but the call I make to get the SmsManager returns null and is therefore useless, regardless of whether the app is open.我不太精通各种上下文,但我认为 applicationContext 会在应用程序的生命周期内存在,但我为获取 SmsManager 所做的调用返回 null ,因此无论应用程序是否打开都是无用的.

Call to service in main activity:在主要活动中调用服务:

val textServiceIntent = Intent(this@MainActivity, TextManager::class.java) 
applicationContext.startForegroundService(textServiceIntent)

Call to getSystemService, returning null:调用 getSystemService,返回 null:

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
 val sms = applicationContext.getSystemService(SmsManager::class.java)
}

Note: I did also try putting this inside onCreate() where super.onCreate() is called, same issue.注意:我也尝试将它放在调用 super.onCreate() 的 onCreate() 中,同样的问题。

Is there some other way of getting the context to access the SmsManager or any other system service inside of a service process?是否有其他方法可以获取上下文以访问 SmsManager 或服务进程内的任何其他系统服务?

Would passing a context from the main activity where it is first called be wise since the service will outlast the app being open?从第一次调用它的主要活动传递上下文是否明智,因为该服务将比打开的应用程序更持久?

Use that if your target SDK < 31 (S)如果您的目标 SDK < 31 (S),请使用它

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    applicationContext.getSystemService<SmsManager>(SmsManager::class.java)
} else {
    SmsManager.getDefault()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM