我试图实现一个能够阅读通知的功能,而且似乎我发现了一个错误,因为onNotificationPosted()
的{{1}}从未被调用过。我配置了清单,正确修改了安全设置,甚至手动启动了服务,但没有做任何事情。可以在模拟器中测试它不是最好的方法。
这是Notification getter类:
NotificationListenerService
(对不正确的缩进)
这是我应该响应广播的片段:
/**
* 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) {
}
}
The Manifest:
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>
然后什么都没有。我已经查看了SO上的所有线程,但可能遗漏了一些非常简单的东西。
答案 0 :(得分:0)
在设置中启用通知访问权限:
if (Settings.Secure.getString(this.getContentResolver(), "enabled_notification_listeners").contains(getApplicationContext().getPackageName())) {
//Add the code to launch the NotificationService Listener here.
} else {
//Launch notification access in the settings...
getApplicationContext().startActivity(new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
}