Hello Friends,
Today, I am going to share a small tutorial on android "NotificationListenerService"
which help us to read the all app notifications. This tutorial covers following
points.
Feature:
1. We can easily read the notification of other android application or read all status bar
notification,
2. Read|Listen incoming whatsapp messages
3. Read all incoming SMS
4. Read all incoming calls
5. Battery Low
Step1 : Create a Notification Service Class :
This class extends NotificationListenerService class which contains
two method:
a) onNotificationPosted(StatusBarNotification sbn) :
Implement this method to learn about new notifications as they are
posted by apps.
b) onNotificationRemoved(StatusBarNotification sbn) :
Implement this method to learn when notifications are removed.
Note: The StatusBarNotifcation object contains extras, app package name and
ticker name
1. NotificationService.java
2.MainActivity.java
4. Android check Notification Access Setting is enable or not:
Download Complete Code From Here : NotificationListener
Hope, this will helps someone.
Enjoy Coding .... :)
Today, I am going to share a small tutorial on android "NotificationListenerService"
which help us to read the all app notifications. This tutorial covers following
points.
Feature:
1. We can easily read the notification of other android application or read all status bar
notification,
2. Read|Listen incoming whatsapp messages
3. Read all incoming SMS
4. Read all incoming calls
5. Battery Low
Step1 : Create a Notification Service Class :
This class extends NotificationListenerService class which contains
two method:
a) onNotificationPosted(StatusBarNotification sbn) :
Implement this method to learn about new notifications as they are
posted by apps.
b) onNotificationRemoved(StatusBarNotification sbn) :
Implement this method to learn when notifications are removed.
Note: The StatusBarNotifcation object contains extras, app package name and
ticker name
1. NotificationService.java
package android.notifications; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import android.support.v4.content.LocalBroadcastManager; import java.io.ByteArrayOutputStream; /** * Created by mukesh on 19/5/15. */ public class NotificationService extends NotificationListenerService { Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); } @Override public void onNotificationPosted(StatusBarNotification sbn) { String pack = sbn.getPackageName(); String ticker =""; if(sbn.getNotification().tickerText !=null) { ticker = sbn.getNotification().tickerText.toString(); } Bundle extras = sbn.getNotification().extras; String title = extras.getString("android.title"); String text = extras.getCharSequence("android.text").toString(); int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON); Bitmap id = sbn.getNotification().largeIcon; Log.i("Package",pack); Log.i("Ticker",ticker); Log.i("Title",title); Log.i("Text",text); Intent msgrcv = new Intent("Msg"); msgrcv.putExtra("package", pack); msgrcv.putExtra("ticker", ticker); msgrcv.putExtra("title", title); msgrcv.putExtra("text", text); if(id != null) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); id.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); msgrcv.putExtra("icon",byteArray); } LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Log.i("Msg","Notification Removed"); } }
2.MainActivity.java
package android.notifications; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import java.util.ArrayList; /** * Created by mukesh on 19/5/15. */ public class MainActivity extends Activity { ListView list; CustomListAdapter adapter; ArrayList3. AndroidManifest.xmlmodelList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); modelList = new ArrayList (); adapter = new CustomListAdapter(getApplicationContext(), modelList); list=(ListView)findViewById(R.id.list); list.setAdapter(adapter); LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg")); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent intent = new Intent( "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private BroadcastReceiver onNotice= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // String pack = intent.getStringExtra("package"); String title = intent.getStringExtra("title"); String text = intent.getStringExtra("text"); //int id = intent.getIntExtra("icon",0); Context remotePackageContext = null; try { // remotePackageContext = getApplicationContext().createPackageContext(pack, 0); // Drawable icon = remotePackageContext.getResources().getDrawable(id); // if(icon !=null) { // ((ImageView) findViewById(R.id.imageView)).setBackground(icon); // } byte[] byteArray =intent.getByteArrayExtra("icon"); Bitmap bmp = null; if(byteArray !=null) { bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); } Model model = new Model(); model.setName(title +" " +text); model.setImage(bmp); if(modelList !=null) { modelList.add(model); adapter.notifyDataSetChanged(); }else { modelList = new ArrayList (); modelList.add(model); adapter = new CustomListAdapter(getApplicationContext(), modelList); list=(ListView)findViewById(R.id.list); list.setAdapter(adapter); } } catch (Exception e) { e.printStackTrace(); } } }; }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.notifications"> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="android.notifications.MainActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="android.notifications.NotificationService" android:label="@string/app_name" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SER VICE"> <intent-filter> <action android:name="android.service.notification.NotificationLi stenerService" /> </intent-filter> </service> <receiver android:name="android.notifications.IncomingSms"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> <receiver android:name=".ServiceReceiver" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> </application> </manifest>
4. Android check Notification Access Setting is enable or not:
//check notification access setting is enabled or not public static boolean checkNotificationEnabled() { try{ if(Settings.Secure.getString(MainActivity.mActivity.getContentResolver(), "enabled_notification_listeners").contains(App.getContext().getPackageName())) { return true; } else { return false; } }catch(Exception e) { e.printStackTrace(); } return false; }
Download Complete Code From Here : NotificationListener
Hope, this will helps someone.
Enjoy Coding .... :)
awsome work Mukesh , this post is very informative and helpful
ReplyDeletehelped me a lot
Thanks and welcome
Deletedude i used your code in my project it gives the null pointer exception in the bitmap object it says that the boolean android bitmap compress
ReplyDeletefor which app you are fetching the image...in some app notification we didn't received image so in that case I am showing app icon launcher.
Deletei am fetching for the whatsapp in my phone .. and its showing me that error
ReplyDeleteand please send me your mail id mine is chauhanadit7@gmail.com so that i can mail you instead of commenting
Sure, my id is: himky02@gmail.com
DeleteThis app reads all notifications? If I receive the first notification I can read all informations, but when I receive the second notification I cant- read all informations because it is append to first notifications. In the status bar the two notifications of same app are in an only notification. How can I read it?
ReplyDeleteits working fine but when my app is closed am not getting notification so can you please share code for that also... thanks in advance
ReplyDeletemy id id pawanvijay02@gmail.com
thanks for this code...am not getting notifications when my app is closed can you please send me code for that also? my id is pawanvijay02@gmail.com
ReplyDeletethanks in advance
Hello Pawan,
Deleteadd start sticky in notification service class.
hi, can you plase send me a code for reading whatsapp messages into android app.
ReplyDeleteI am new to android app development
Hello ,
DeleteI already attach the complete code in this post. Check it.
Its helps to read your whatsapp messages too.
Bute while i run this code from github, nothing is displayed below the actionbar with heading remote notification.
ReplyDeleteMay be you didn't enable the Notification listener from setting menu, turn on and then try.
DeleteHow to turn on it.?
ReplyDeleterun it on android 4.3 and above and check setting
Deletemenu from top right.See the screen shot above....
how can i enable it?
ReplyDeleteI enabled it. Even though app crashes. please help
ReplyDeleteCan you please give the code that reads only whatsapp messages?
ReplyDeleteHi. Thanks a lot for this code. I wonder how to run this app in background right from boot up. Currently it works, only if I open it.
ReplyDeletesame thing i want...
DeleteDear mukesh if it is possible provide some guide and code for this...
same thing i also want.
Deletehi Mukesh if any solutions is there plz kindly share the information regarding this.
Hi Mukesh,
ReplyDeletebrilliant code... well done, but yaar i have 1 question.
this is listening to all the incoming/or going to be coming Notifications...
Now what if i want it to give me a list of present(Current) notifications that are alive in the StatusBar.. but havent been attended to?
So basically it should be able to extract the same from an already existing notification when i have started your app...
Please guide me how to go about doing so.. thanx
Hi, the code is good, but i can read only first Whatsapp's notification. The other notification it doesn't read, it read in android.text this:" 2 new messagges". I would read the text of the messagges
ReplyDeleteHello Chiara,
ReplyDeleteadd below code which helps you to read whatsapp's second
notifcation text or evrey message one by one:
String text = null;
if (extras.getCharSequence("android.text") != null) {
text = extras.getCharSequence("android.text").toString();
}
if (text == null) {
// for whatsapp on kitkat second whats app text
// will be null
if (extras.get("android.textLines") != null) {
CharSequence[] charText = (CharSequence[]) extras
.get("android.textLines");
if (charText.length > 0) {
text = charText[charText.length - 1].toString();
}
}
}
Why error This code "Bundle extras = sbn.getNotific ation().extras;", in Ecclipse sdk 18
ReplyDelete"Extras no be resolved and not a field"?
Hey Thank you so much.. It is very informative. However, why it does not catch notifications from few Apps like Way2 news and of moneycontrol
ReplyDeleteHi,
ReplyDeleteThanks for this tutorial.I was able to get it work.I have two problems though
1.I need to show corresponding app icon on notification and on click i must open the same app
2.When i navigate screen the previous notification that are present in statusbar aren't shown in app.I want to show until user click clear notification.
So kindly help me to solve this.Email me @ themebowlapps@gmail.com
Hi,How to show corresponding app icon on left side of notification rather than default icon?
ReplyDeleteHello Govind,
Deletecheck below block of code where I am checking if there is a user profile then we are showing his pic else default app launcher icon.
Modify the code acc. to you.
if(id != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
id.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
msgrcv.putExtra("icon",byteArray);
}
Hi,
DeleteThanks for your immediate response.I already tried this code.But all i see is default icon on side for all apps.I don't see whatsapp icon for whatsapp msg nor default system message icon for sms.I m stuck.Kindly help me to find a solution
Okay, you need default icon then add this block of code in else part(
ReplyDeleteif no whats app profile pic the get default laucher icon )
if(id != null) {
}else{
if (pack != null) {
Drawable d = getPackageManager()
.getApplicationIcon(pack);
Bitmap bitmap = ((BitmapDrawable) d)
.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(
Bitmap.CompressFormat.JPEG,
100, stream);
byte[] bitmapdata = stream
.toByteArray();
}
}
}
which min API I need to use NotificationListener ?
ReplyDeleteApi 17 and above
DeleteThanks a lot Mukesh for the code. I think you should also make video tutorials as your a very talented guy and it would help a lot of people.
ReplyDeleteThanks dear will try to make the youtube video blog.
Deletein my code CustomListAdapter cannot be resolved to a type..
ReplyDeleteHow do I solve this?
Show me the code..may be because you didn't closing the
Deletebrackets properly.
Hello, Firsly thanks for post. I took source code and run. it runs , when facebook or other apss notifications comes, it shows but for whatsapp it doesn't . Second one is when i close app it doesnt work. Can u explain the solution for these two problems ?
ReplyDeleteHello,
Deleteadd below code which helps you to read whatsapp's second
notifcation text or evrey message one by one:
String text = null;
if (extras.getCharSequence("android.text") != null) {
text = extras.getCharSequence("android.text").toString();
}
if (text == null) {
// for whatsapp on kitkat second whats app text
// will be null
if (extras.get("android.textLines") != null) {
CharSequence[] charText = (CharSequence[]) extras
.get("android.textLines");
if (charText.length > 0) {
text = charText[charText.length - 1].toString();
}
}
}
FOr your second query make service always runnable in backgaround
For running this app in background you can use service class.
ReplyDeleteNice coding..
Hi Mukesh! I posted on Stackoverflow here:
ReplyDeletehttp://stackoverflow.com/questions/42056739/capture-notifications-and-send-to-my-server
I haven't a clue how to use your code but it looks like what I need... I want the notifications to be sent to a URL on my server.
How can I do this?
-Ken
Whatsapp notification messages is not showing,it null pointer at place of
ReplyDeleteString text = extras.getCharSequence("android.text").toString();
text is null;
while title and package is showing.
hi thanks for your post. when i close this app it doesnt show any notifications, please solve this one
ReplyDeleteIs it possible, in the case of Whatsapp, to get the image that is sent as a message?
ReplyDeleteIs it possible, in the case of Whatsapp, to get the image that is sent as a message?
ReplyDeletedude u are a saviour...
ReplyDeletewhole day spent on this n finally got your post
thanx for this post.
but if i want to store these notifications in array or a varaible instead of listview, will it be possible, if yes kindly share the answer plz...
Yes you can make Arraylist of Model class where you can store the data. I don't know your exact requirement but what i suggest is storing the model class data in DB is a best way.
DeleteThanx a lot Mr Yadav, you saved my life
ReplyDeleteString text = null;
ReplyDeleteif (extras.getCharSequence("android.text") != null) {
text = extras.getCharSequence("android.text").toString();
}
if (text == null) {
// for whatsapp on kitkat second whats app text
// will be null
if (extras.get("android.textLines") != null) {
CharSequence[] charText = (CharSequence[]) extras
.get("android.textLines");
if (charText.length > 0) {
text = charText[charText.length - 1].toString();
}
}
}
Where to put this code. Plus is there anywhy to get gallery pictures or incoming pictures.
Is it possible that on starting the application, it will give access to the notification access?
ReplyDeletem trying for 2 days for this, if possible plz send the code for that.
is it possible to detect every incoming n outgoing notification(even they r not in notification bar)
ReplyDeletelike incoming call, message, whatsapp, fb everything.
I want show only notification app icon not all message on screen lock
ReplyDeletehi, mukesh!
ReplyDeleteis there any code to read all upcoming images from whatsapp and then locate them into the listview? i'm trying to use some codes, but neither of them are working.
thanks for the code above, very good work!
hi, mukesh!
ReplyDeleteis there any code for reading upcoming images from whatsapp and then loading them into the listview?!
i was trying a bunch of codes but neither of them are working!
Your code for notifications is awesome, dude, good work!
Read Send Message is not working is there any error in my code then pls check it
ReplyDeleteimport android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = null;
if (extras.getCharSequence("android.text") != null) {
text = extras.getCharSequence("android.textLines").toString();
}
if (text == null) {
// for whatsapp on kitkat second whats app text
// will be null
if (extras.get("android.textLines") != null) {
CharSequence[] charText = (CharSequence[]) extras
.get("android.textLines");
if (charText.length > 0) {
text = charText[charText.length - 1].toString();
}
}
}
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
Read Send Message is not working is there any error in my code then pls check it
ReplyDeleteimport android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = null;
if (extras.getCharSequence("android.text") != null) {
text = extras.getCharSequence("android.textLines").toString();
}
if (text == null) {
// for whatsapp on kitkat second whats app text
// will be null
if (extras.get("android.textLines") != null) {
CharSequence[] charText = (CharSequence[]) extras
.get("android.textLines");
if (charText.length > 0) {
text = charText[charText.length - 1].toString();
}
}
}
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
how to get hatsapp number from notification detail?
ReplyDeleteHello Kanika,If the number saved on your device then it will show you contact name else it will show mobile number on ticker, you have to fetch number based on name if it is saved.
DeleteHi Mukesh , whatsapp messages are not working pls help me
ReplyDeleteIn first place I'd like to thank you Muskesh for sharing the code. Then I'd like to ask for your help. I've seen over the coments here that you guided some people to insert a stretch of code to solve some problems and to improve the app, but I didn't understand where to inset these codes. Could you guide me?
ReplyDeleteAnother thing is that I'm getting the message "Unhandled exception: android.content.pm.PackageManager.NameNotFoundException" in the stretch of code below:
Drawable d = getPackageManager().getApplicationIcon(pack);
Thanks for the blog. It helps to read the basic details from the StatusBarNotification. Can you also provide details on how to read the actions on the notification. I need to deep link to the app that posted the notification.
ReplyDeleteCan you also please help on How to read the intent on the received notification?
ReplyDeleteHi mukesh, thanks for this ultimate post. But I want to know that there are three classes IncomingSms, NotificationService, ServiceReceiver. Can u plz elaborate the working of these classes , I mean what they are exactly working in the project. Thanks in advance.
ReplyDeleteNot working 7.1.1 Nougat upgrade this code
ReplyDeleteUsed the same code but it is not working in Nougat
ReplyDeleteHi
ReplyDeleteMukesh
Is there any way we can read notification without accessibility by user /done programmatically
once application install it read all notification
I can able to read email notification but i cant read the body of the email ?.
ReplyDeletehello.. i used your code for listening whatsapp notification but it duplicating the notification. how could i resolv this issue? thanks in advance.
ReplyDeleteHey Mukesh,
ReplyDeleteI am not getting any thing in the app.
Can someone help me.
hello there how i can create this service as background as im using START_STICKY but it is not working
ReplyDeletecan you help me?