我正在尝试实现一个能够读取通知的功能,而且似乎我有一个错误,因为onNotificationPosted()
的NotificationListenerService
从未被调用过。我配置了清单,正确修改了安全设置,甚至手动启动了服务,但没有做任何事情。可以在模拟器中测试它不是最好的方法。
这是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上的所有线程,但可能会遗漏一些非常简单的东西。
在您的设置中启用通知访问权限:
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"));
}