我希望你能帮助翻译关于IT技术的内容。以下是需要翻译的内容,其中涉及到NotificationListenerService。
我一直在尝试使用NotificationListenerService,但是进展不顺利。我已经尝试了很多方法,特别是在so网站上找到的方法。但是它的工作效果并不稳定。
首先看一下代码:
清单文件:
<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());
}
}
在主 Activity 中启动服务,或者如果需要,请求用户启用设置:
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,否则它永远不会自己启动。但是同样地,它仅适用于第一次启动,永远不再起作用,直到取消选中-重新检查安全设置...
我错过了一些明显的东西吗?