Android 在调试模式下运行时未启动通知侦听器服务
我正在使用NotificationListenerService构建一个应用程序。但当我在调试模式下运行应用程序时,服务总是不会启动。我将代码缩减为以下内容: 我的活动:Android 在调试模式下运行时未启动通知侦听器服务,android,android-service,android-notifications,Android,Android Service,Android Notifications,我正在使用NotificationListenerService构建一个应用程序。但当我在调试模式下运行应用程序时,服务总是不会启动。我将代码缩减为以下内容: 我的活动: class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVi
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
}
}
当然,我在清单中添加了以下内容:
<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
中获得日志输出服务运行:false
。正常启动时该值为真,无需调试。出了什么问题以及如何解决?好的,最后我没有一个完整的解决方案,但有一种改进,接近于有效的解决方案
那么,我的原始应用程序代码中的技术问题到底是什么呢?我是如何解决这些问题的
NLService
class'onConnect()
方法中进行了一些初始化。我将所有初始化都移动到onListenerConnected()
,添加了处理程序.postDelayed(runnable,500)代码>
NLService
类中创建了一个类的对象(我们称之为MyHandlerClass
),并将对服务的引用传递给它。这不是一个好的解决方案,因为Android在NotificationListenerService
中:
在执行此操作之前,服务应等待onListenerConnected()事件
MyHandlerClass
中,我调用了nlService.getActiveNotifications()
。这个调用是在Android调用NLService之前发出的。因此,我为NLService
中的方法制作了包装,例如:
fun getActiveNotifications(): Array<StatusBarNotification>?
{
return if (isConnected)
{
super.getActiveNotifications()
}
else
{
null
}
}
fun getActiveNotifications():数组?
{
如果(未连接)返回
{
super.getActiveNotifications()
}
其他的
{
无效的
}
}
我在onListenerConnected()
和onListenerDisconnected()中切换布尔变量isConnected
现在,在调试模式下运行应用程序时,服务仍然会崩溃。但是,在正常模式下运行时,所述改进可以减少碰撞量。这可能是时间问题。Android启动了你的通知ListenerService
,你可能没有给它足够的时间。你说没有给它足够的时间是什么意思?你能更详细地描述一下吗?您认为我是否可以在onListenerConnected()中快速启动?所以我应该用postdayed来初始化这个方法中的东西吗?或者您认为我每次都应该在onListenerConnected()之前调用requestRebind()吗?现在调用requestRebind()是我在检测到服务未运行时立即重新连接服务的备用方法。您应该发布更多代码或尝试确定服务
崩溃的原因。你没有提供足够的信息来帮助你。但是为什么服务器会崩溃呢?发布带有异常和stacktrace的日志猫。您可能需要拆下logcat过滤器以查看问题。
fun getActiveNotifications(): Array<StatusBarNotification>?
{
return if (isConnected)
{
super.getActiveNotifications()
}
else
{
null
}
}