Android : Custom alert on Receiving sms

on Sunday, August 3, 2014


I am trying to write an application where I am intercepting in-coming sms.


That works fine.


Now when I am trying to set my own notification for it, it doesn't show.


Here is the code :



package sms;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

import com.pbc.connect2.StartActivity;

@SuppressWarnings("deprecation")
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();


@Override
public void onReceive(Context context, Intent intent) {

this.abortBroadcast();

// TODO Auto-generated method stub
final Bundle bundle = intent.getExtras();

try {

if (bundle != null) {

final Object[] pdusObj = (Object[]) bundle.get("pdus");

for (int i = 0; i < pdusObj.length; i++) {

SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();

String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();

showNotification("senderNum: "+ senderNum + ", message: " + message, "New Msg", context);

} // end for loop
} // bundle is null

} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);

}
}

private void showNotification(String eventtext, String Title, Context ctx) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

// Set the icon, scrolling text and timestamp
@SuppressWarnings("deprecation")
Notification notification = new Notification(0,
"Alert", System.currentTimeMillis());

// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, StartActivity.class), 0);

// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(ctx, Title, eventtext,
contentIntent);
notification.sound = alarmSound;
notification.ledOnMS = 5;
// Send the notification.
notificationManager.notify("Title", 0, notification);
}

}


I've debugged through the code and I see them executing. But the notification doesn't show.


The function showNotification() isn't working and all I get the system default notification. Where am I going wrong ? Some help will be appreciated.


0 comments:

Post a Comment