我在没有很多运气的情况下与NotificationListenerService进行对抗。我尝试了很多在这里和那里发现的食谱,特别是在那儿……但是它的工作方式却前后不一致。
首先看一下代码:
显现 :
<service
android:name=".services.NLService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
然后,服务本身:
public class NLService extends NotificationListenerService {
private String TAG = "NLService";
// bind and unbind seems to make it work with Android 6...
// but is never called with Android 4.4...
@Override
public IBinder onBind(Intent mIntent) {
IBinder mIBinder = super.onBind(mIntent);
Log.i(TAG, "onBind");
return mIBinder;
}
@Override
public boolean onUnbind(Intent mIntent) {
boolean mOnUnbind = super.onUnbind(mIntent);
Log.i(TAG, "onUnbind");
isNotificationAccessEnabled = false;
try {
} catch (Exception e) {
Log.e(TAG, "Error during unbind", e);
}
return mOnUnbind;
}
// onCreate is called with Android 4.4
// because the service is explicitly started from the MainActivity.
// Not on Android 6 where the system binds this service itself...
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "********** onCreate");
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG, "********** onNotificationPosted");
Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG, "********** onNOtificationRemoved");
Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
}
}
然后在主活动中启动服务,或者如果需要,我们要求用户启用设置:
if (!Utilities.hasNotificationAccess(this))
{
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
Log.i(TAG,"hasNotificationAccess NO");
}
else
{
Log.i(TAG,"hasNotificationAccess YES");
// without this startService, it never works with Android 4.4...
// but this is not needed in Android 6...
Intent mServiceIntent = new Intent(this, NLService.class);
startService(mServiceIntent);
}
显然,已启用通知的安全设置访问权限...
在Android 6上:
在NLService本身上,添加了onBind和onUnbind方法使其可以工作,我可以查看onBind日志,并且可以很好地触发onNotificationPosted。但是它一直持续到应用程序的下一次启动,然后不再绑定,也没有onNotificationPosted,直到我返回安全设置以取消选中-重新检查通知访问权限,什么都没有发生:每次启动应用程序时都无法重复在生产环境中。
在Android 4.4上:
与Android 6相比,在MainActivity中,我需要显式启动NLService,否则它永远不会自行统计。但是它再次适用于首次启动,并且直到取消选中-重新检查安全设置后才可以使用...
我错过了明显的事情吗?
Android缓存存在问题。在设备上上传应用程序时,操作系统会将您的服务连接到Notification Manager。如果您之前运行过应用程序,则Android会在缓存中找到此服务,因此不会重新连接。
解决方法:在设备上推送该应用程序之前,重命名您的服务(Android Studio中的“重构”选项效果很好)-Android会将这项服务识别为新服务并连接到Notification Manager。
https://developer.android.com/reference/android/service/notification/NotificationListenerService.html#onListenerConnected()-连接到Notification Manager后将调用此方法,以便您可以检查服务是否已连接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句