我正在使用NotificationListenerService构建一个应用程序。但当我在调试模式下运行应用程序时,服务始终不会启动。我将代码缩减为以下内容:
我的活动:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
startActivity(intent)
}
override fun onResume() {
super.onResume()
val isServiceRunning = isMyServiceRunning(NLService::class.java)
Log.i("MainActivity", "service running: " + isServiceRunning)
}
private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}
服务:
class NLService : NotificationListenerService() {
private val TAG: String? = "NLService"
override fun onBind(intent: Intent): IBinder? {
Log.i(TAG, "onBind()")
return super.onBind(intent)
}
override fun onCreate() {
super.onCreate()
Log.i(TAG, "onCreate()")
}
override fun onDestroy() {
super.onDestroy()
}
override fun onNotificationPosted(sbn: StatusBarNotification?) {
Log.i(TAG, "onNotificationPosted() sbn: $sbn")
super.onNotificationPosted(sbn)
}
}
当然我在清单中添加了这个:
<service
android:name=".NLService"
android:label="MyNLService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
当以调试模式启动应用程序时,我总是会得到日志输出service running: false
in onResume
。正常启动时该值为 true,无需调试。出了什么问题以及如何解决?
好吧,最后我没有一个完整的解决方案,但有一种接近工作解决方案的改进。
那么实际上存在哪些技术问题呢?我原来的应用程序代码?我是如何解决这些问题的?
- 我做了一些初始化
NLService
class' onConnect()
方法。我将所有这些初始化移至onListenerConnected()
,添加一个handler.postDelayed(runnable, 500);
.
- I created an object of a class (Let's call it
MyHandlerClass
) within the NLService
class and passed a reference to the Service into it. This is not a good solution because Android documentation says something about many methods https://developer.android.com/reference/android/service/notification/NotificationListenerService.html#getActiveNotifications(java.lang.String%5B%5D) within the NotificationListenerService
:
在执行此操作之前,服务应等待 onListenerConnected() 事件。
So in MyHandlerClass
我打电话给一个nlService.getActiveNotifications()
。已拨打此电话maybe在 Android 调用之前NLService
s' onListenerConnected
。所以我为里面的方法做了包装NLService
,例如:
fun getActiveNotifications(): Array<StatusBarNotification>?
{
return if (isConnected)
{
super.getActiveNotifications()
}
else
{
null
}
}
我切换了布尔变量isConnected
within onListenerConnected()
and onListenerDisconnected()
现在,在调试模式下运行应用程序时,服务仍然崩溃。但在正常模式下运行时,崩溃的数量可以通过所描述的改进来减少。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)