在调试模式下运行时,通知侦听器服务未启动



我正在使用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>

在调试模式下启动应用程序时,我总是在onResume中获取日志输出service running: false。正常启动时,该值为 true,无需调试。出了什么问题以及如何解决?

好的,最后我没有一个完整的解决方案,而是一种接近工作解决方案的改进。

那么我的原始应用程序代码中实际上有哪些技术问题?我是如何解决它们的?

  1. 我在类onConnect()方法中进行了一些初始化NLService。我将所有这些初始化移到onListenerConnected(),添加一个handler.postDelayed(runnable, 500);
  2. 我在NLService类中创建了一个类的对象(我们称之为MyHandlerClass),并将对服务的引用传递给其中。这不是一个好的解决方案,因为Android文档说明了NotificationListenerService中的许多方法:

    在执行此操作之前,服务应等待 onListenerConnected() 事件。

所以在MyHandlerClass我打电话给nlService.getActiveNotifications().这个电话可能是在Android打电话给NLServiceonListenerConnected之前打的。所以我为NLService内部的方法制作了包装器,例如:

fun getActiveNotifications(): Array<StatusBarNotification>?
{
return if (isConnected)
{
super.getActiveNotifications()
}
else
{
null
}
}

我在onListenerConnected()onListenerDisconnected()中切换了布尔变量isConnected

现在,在调试模式下运行应用程序时,服务仍然崩溃。但是在正常模式下运行,可以通过描述的改进来减少崩溃的数量。

最新更新