通知监听器 - onNotificationPosted不起作用

时间:2018-05-05 17:55:16

标签: java android notifications android-notifications notification-listener

我已尝试过所有类型的解决方案和代码,但这些解决方案都适用于我,而且我不知道为什么。请帮帮我。

我的MainActivity代码是:

if(isNotificationServiceEnabled())
    {
        Intent i= new Intent(this,NotificationsService.class);
        i.putExtra("command", "get_status");
        startService(i);
    }
    else
        startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));

现在我只是尝试检查该服务是否已发布nostification,但是从日志中我只能看到它进入 onCreate 方法,但 onNotificationPosted

这是我的服务类的代码:

public class NotificationsService extends NotificationListenerService {

@Override
public void onListenerConnected(){
    Log.d(TAG, "Connected");
}

@Override
public void onNotificationPosted(final StatusBarNotification sbn){

    Log.d(TAG,"got it");

}

我也尝试过使用广播服务的解决方案,但它仍然无法正常工作。

感谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。在我的代码中我遇到了一些问题,但后来我在其他项目中测试了有关通知监听器的其他代码,并且它工作正常。那么我修改我的代码,现在它可以工作。

关于通知lisener您无需启动该服务,因为启动应用程序时会启动该服务。所以我只是对我的代码进行了更改:

主要

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if(!isNotificationServiceEnabled())
    {
        startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
    }

}
@Override
protected void onDestroy() {
    super.onDestroy();
} 

在服务中我只是将日志代码写入调试通知包中。

相反,我得到的广播仅用于在服务和我的活动之间交换数据,例如在文本视图中编写通知。

相关问题