Read content from notification parcelable objects for consequent notification - android

I am trying to build Whatsapp Notification filtering app, where I monitor all notification from Whatsapp and remove messages as per filtering policy.
I can fetch message content using below link code
Extract notification text from parcelable, contentView or contentIntent for first message only
but the problem is I can fetch only first message, if user does not read first message then second message onwards I get only "2 messages from sender" instead of actual message.
NOTE: I am getting
android.text = actual message for first message but its null from second message/notification onwards
android.title = sender
android.summaryText = "n new messages"
any help would be appreciated.

Yes, finally after few hours of googling I design a code which does work for me.
Bundle extras = sbn.getNotification().extras;
CharSequence[] lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
JSONArray s = new JSONArray();
for (CharSequence msg : lines) {
msg = removeSpaces(msg);
if (!TextUtils.isEmpty(msg)) {
s.put(msg.toString());
}
}
private static String removeSpaces(#Nullable CharSequence cs) {
if (cs == null)
return null;
String string = cs instanceof String ? (String) cs : cs.toString();
return string.replaceAll("(\\s+$|^\\s+)", "").replaceAll("\n+", "\n");
}
here JSONArray s contains all messages that I want

Related

Android- read incoming messages using broadcast receiver

I have created an android application that listens for incoming sms. The issue i am encountering is that it also reads previous sms. The goal of the app was to grab sms from a specific originating address and store it in a database.
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i(TAG, "Intent Received: "+intent.getAction());
if (intent.getAction()==SMS_RECEIVED){
Bundle dataBundle = intent.getExtras();
if(dataBundle != null){
//creating PDU protocol Data unit object which is a protocol for transferring message
Object[] mypdu = (Object[])dataBundle.get("pdus");
final SmsMessage[] message = new SmsMessage[mypdu.length];
for(int i =0; i< mypdu.length; i++){
//for build version >= API
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String format = dataBundle.getString("format");
//From PDU we get all object and smsMessage using following line of code
message[i] = SmsMessage.createFromPdu((byte[])mypdu[i],format);
}else{
message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i]);
}
msg += message[i].getMessageBody().toString().replace("null","");
originatingAddress = message[i].getOriginatingAddress();
}
msg = msg.replace("null","");
if(originatingAddress.trim().equals("MPESA")) {
Toast.makeText(context.getApplicationContext(), "message: " + msg, Toast.LENGTH_SHORT).show();
}
}
}
// throw new UnsupportedOperationException("Not yet implemented");
}
}
Please try with below way
(1)The Simple way you can achieve to store the unique of record on every SMS is timestamp is only unique in this case whenever you get SMS store timestamp of every Sms as a Unique or primary key as you want in database, like system.currentTimeMillisecond to get time of current SMS and store as LONG type Column in your database,
(2) you can also check with unique time on every SMS get but it is complex to check with every existing records
Hope this process will help in your way with prevent of duplicate record store in database

Android email client app tracking unread gmail emails

So I've been using javamail API as part of my android app. After a login to a gmail account, the user can write new emails, check the inbox and sent mails. The emails are displayed in a listview with the help of an adapter class. (more accurately the sender, the subject and the sending date is displayed, and if the user clicks on the listview item, then the mail content will be displayed too on a new activity). All this is working well.
I would like to display unread emails differently (unread in the gmail client too), like set the textSyle bold if the mail is unread, but i'm having trouble adding this feature. I've been trying to check the flags of each fetched email message, but for some reason i dont see these flags in the variables.
My code snippet for fetching the mails (display is not here, that's in the adapter class):
protected ArrayList<Email_Message> doInBackground(Void... args) {
try {
Properties properties = new Properties();
properties.put("mail.store.protocol", "imaps");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imaps");
store.connect("imap.gmail.com", username, password);
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_WRITE);
Flags flags2 = emailFolder.getPermanentFlags(); //has 2 weird user flags in it ($phishing, $notphising) and systemflags = -2147483061 ???
Flags seen = new Flags(Flags.Flag.RECENT);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message messages2[] = emailFolder.search(unseenFlagTerm); //this will net the same result as getMessages(), only here for testing
int test = emailFolder.getUnreadMessageCount(); //as far as i can tell this is working (i have 5000+ emails and 37 them are unread somewhere) but when i get a new email and the number goes up by 1 (38), and if i run the code again, after i already fetched the mails once, it's gonna be 37 again, and the mail marked as read in my gmail webclient too
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
int j = messages.length - 1;
for (int i = j - startIndex; i > j - startIndex - offset && i > (-1); i--) { //startIndex and offset are for displaying only 10 messages at the start and loading another 10 if the user scrolls to bottom
if (isCancelled()){
break;
}
Email_Message mailMessage = new Email_Message(); //my class for storing email messages
mailMessage.messageType = 1;
//some tricks to get the address in the right format
Address[] email_address = messages[i].getFrom();
String tempAddress = email_address[0].toString();
tempAddress = MimeUtility.decodeText(tempAddress);
//still tempering with address, not important
if(tempAddress.contains("=?")){
String[] AddressParts = tempAddress.split("\\?=");
mailMessage.messageAddress = AddressParts[1].substring(2);
}
else {
mailMessage.messageAddress = tempAddress;
}
Flags flags = messages[i].getFlags(); //user_flags = null, system_flags = 32
Flags.Flag[] systemflags = flags.getSystemFlags(); //has 1 item in it: bit = 32
String str[]= flags.getUserFlags(); //empty, these are all true for all my mails, not just one
mailMessage.messageDate = messages[i].getSentDate().toString();
mailMessage.messageSubject = messages[i].getSubject();
Object msgContent = messages[i].getContent();
String content = ""; //getting the content of the mail with these multipart stuffs
if (msgContent instanceof Multipart) {
Multipart multipart = (Multipart) msgContent;
Log.e("BodyPart", "MultiPartCount: " + multipart.getCount());
for (int k = 0; k < multipart.getCount(); k++) {
BodyPart bodyPart = multipart.getBodyPart(k);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) {
DataHandler handler = bodyPart.getDataHandler();
content = handler.getName();
} else {
content = bodyPart.getContent().toString();
}
}
} else
content = messages[i].getContent().toString();
mailMessage.messageContent = content;
EmailInbox.add(mailMessage);
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return EmailInbox;
}
I put some comments in the code to explain what i've found in the flags. What can I do to make this work? I already predict problems, like what happens after I read an unread mail in my app only, set its flag to seen, and when I start the activity again and fetch the mails, it's gonna be unread again, since I don't store them locally, but that's a problem after I managed to find a solution for this first.
Thanks for any help!
I'm not clear on how you're looking for the flags. Using messages[i].isSet(Flags.Flag.SEEN) will tell you if the SEEN flag has been set. Note that the SEEN flag will normally be set as soon as you access the content of the message, so you should not have to set it yourself.
Hint: use the InternetAddress.toUnicodeString method, or get the name and address separately using the getPersonal and getAddress methods. This will avoid any need to decode them yourself.

GCM and Special characters

I recently changed my c2dm push aaplucation to GCM. A new problem appeared. Its now receiving '?' instead of 'ö','ï', ...
My server logs correct Strings, but the application receives '?' insteads.
Do you think it could have something to do with GCM?
My code is the following:
public static void displayMessage(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String message = (String) extras.get("message");
Log.v("extras", extras.toString());
Util.generateNotification(context, message, intent);
}
}
and the log is then:
10-02 22:18:23.671: V/intent(29809): Bundle[{message={"name":"j?rg"},
message_id=8bb60eee-3a93-4075-b606-40495511a4da, collapse_key=do_not_collapse, from=160085429222}]
Best regards!
I dont think so there is problem in GCM. Try to use UTFEncoding for your message.
String output = new String(name.getBytes("8859_1"), "utf-8");

I can't receive my message in my Android Device through google cloud messaging?

I am using python as server app to send my message to GCM Server to receive on registered android device. I am getting success from GCM server with message id.
On android mobile I am receiving data in arg1 in onMessage() function but with just two keys in arg1, from & collapse_key.
In below Java Code, from key contains a LongInt value & message is null.
Can anybody tell me what thing i am missing in Java Code or in Python Code.?
Here is my JavaCode:
#Override
protected void onMessage(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String keys="";
for (String key : arg1.getExtras().keySet())
keys+=key+"||";
String mess = arg1.getExtras().getString("from");
String mess1 = arg1.getExtras().getString("message");
}
Python Code:
def SelectAction(request,client_id):
if request.method == 'GET':
message = request.GET.get('message','')
if not message:
return Error(message = "Argument Missing.")
registration= Registration.objects.get(registeredUser = user)
values = {}
values['registration_id'] = registration.appId
values['data.message'] = message
param = urllib.urlencode(values)
req = urllib2.Request("https://android.googleapis.com/gcm/send", param)
req.add_header( 'Content-Type' , 'application/x-www-form-urlencoded;charset=UTF-8' )
req.add_header( 'Authorization' , 'key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
response = urllib2.urlopen(req)
reply = {}
if response.read().split('=')[0] == 'id':
reply['error'] = '0'
else:
reply['error'] = '1'
return HttpResponse(json.dumps(reply), mimetype="application/javascript")
else:
return Error()
Try extract the data before you do something else:
Bundle data = intent.getExtras();
if (data != null) {
data.isEmpty(); toString();
}
Now you can use toString(); and see what the data contains:
Log.i("C2DM", data.toString());
check the log for C2DM and paste what you get.
Everything seems to be set up correctly. It seems to me like that the message is never sent in the first place to your server. Since you can retrieve the from but not message, this is probably correct.
In the server, can you change the following line;
values['data.message'] = message
to this;
values['data.message'] = "testMessage"
I think this will most likely lead to you getting the message in android.. Just temporarily change the message to see if the push is working to begin with..

SmsMessage.isEmail() always returns false

So, in my app, I respond to incoming sms, and I'd like to be able to respond to SMS sent by an email address, but isEmail() always returns false, therefore getEmailFrom() and getEmailBody() always return null. Here's my code:
Bundle bundle = intent.getExtras();
String recMsgString = "";
String fromAddress = "";
String tag = "SMS_RECEIVED";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i=0; i<pdus.length; i++){
SmsMessage recMsg = SmsMessage.createFromPdu((byte[])pdus[i]);
recMsgString = recMsg.getMessageBody();
fromAddress = recMsg.getOriginatingAddress();
if (recMsg.isEmail()){
fromAddress = recMsg.getEmailFrom();
recMsgString = recMsg.getEmailBody();
}
}
//do some logging
//code to react to the message
}
}
Any help would be greatly appreciated.
Hrm well I have never heard of a string method called isEmail() - maybe I am missing something?
You declare
String recMsgString = "";
and then try to access
recMsgString.isEmail()
Which does not exist. Also I notice you set recMsgString equal to recMsg.getMessageBody()
recMsg.getMessageBody();
I wouldn't think the getMessageBody() function would return an email anyway.
I think what you meant to do was:
SmsMessage recMsg = SmsMessage.createFromPdu((byte[])pdus[i]);
...
if (recMsg.isEmail()){
fromAddress = recMsg.getEmailFrom();
recMsgString = recMsg.getEmailBody();
}
I kinda/sorta figured something out, but I'm not sure why it worked...
So, in my app instead of checking isEmail and then using getEmailFrom and getEmailBody, I just got the sender (which is something like 14100000011), and then used recMsgString.contains(myKeyword)
My app then sends a message back to 14100000011 and it delivers to my email.
I'm not really sure why it behaves this way, though. I guess AT&Ts email gateway just delivers back to wherever I sent it from. Didn't know this would work.
On a side note, does anyone know the functioning on any other carrier?
That is, if you send an email from gmail (or another email) to your phone number as such:
AT&T: phonenumber#txt.att.net
T-Mobile: phonenumber#tmomail.net
Verizon: phonenumber#vtext.com
Sprint: phonenumber#messaging.sprintpcs.com
Then reply, do you receive a message back in your email?
If anybody is kind enough to test this, please leave a comment saying who your carrier is and who your email provider is and the results of the test.

Categories

Resources