Reputation: 21
Does anyone know how can I check if there are any notifications programmatically in android?
I want to check if there is any notification currently available in the notifications list.
for example, if there is any notification, the LED light is turned on and if the notifications list is cleared, the LED light is turned off.
I just want to know the condition or the code that allow us to check if there are any notifications available in the notifications list.
if ( condition - there are any notifications )
// my code
Upvotes: 2
Views: 3699
Reputation: 15668
You can use NotificationListener
API, which is available on Android 4.3+. To do that you just simply need to create a simple Service
that extends NotificationListenerService
.
Here is some sample code
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
public class NLService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG, "Notification posted");
Log.i(TAG, "ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText + "t" + sbn.getPackageName());
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG, "Notification Removed");
Log.i(TAG, "ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText + "t" + sbn.getPackageName());
}
}
A complete tutorial is available here
Prior to this version of Android, you can make a hack through the AccessibilityService as described here
Upvotes: 3