【发布时间】:2015-02-28 22:59:13
【问题描述】:
我正在尝试实现一个可以读取通知的功能,但我似乎有一个错误,因为 NotificationListenerService 的 onNotificationPosted() 从未被调用过。我配置了清单,正确修改了安全设置,甚至手动启动了服务,但它什么也没做。难道在模拟器中测试它不是最好的方法吗?
这是 Notification getter 类:
/**
* Created by laurentmeyer on 28/02/15.
*/
public class NotificationListener extends NotificationListenerService {
public NotificationListener(){
Log.d("Notification", "Created");
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification mNotification = sbn.getNotification();
Intent intent = new Intent("Msg");
Log.d("Notification", "Received");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Notification", "created");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Notification", "destroyed");
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
}
}
(对不起,缩进不正确)
这是我应该响应广播的片段:
public class VerificationFragment extends BaseFragment implements SMSReceivedCallbacks {
public void onNotificationReceived(int code) {
ed.setText("OK");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(new Receiver(), new IntentFilter("Msg"));
}
// A bunch of other useless stuff
private class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
onNotificationReceived(0);
}
}
}
清单:
<service
android:name=".NotificationListener"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
总结一下,我有:
02-28 11:40:53.236 6585-6585/com.******.laurentmeyer.****** D/Notification﹕ Created
02-28 11:40:53.236 6585-6585/com.******.laurentmeyer.****** D/Notification﹕ created
然后什么都没有。我已经查看了 SO 上的所有线程,但可能遗漏了一些非常简单的内容。
【问题讨论】:
-
您是否在“设置”中为您的服务启用了通知访问权限?
-
是的,当然,这就是我有点失落的原因。因为一切看起来都是正确的!
-
它实际上对我有用。我在 logcat 中看到“已收到”。我已将您的代码精简到最低限度,即删除了所有广播和片段内容。不知道这里发生了什么。
-
如何创建要收听的通知? IE。您是否尝试过单击主要活动中的按钮创建一个,仅用于测试目的?
-
不,我在打电话。
标签: android android-intent notifications