I am new in Android Programming. I have created two classes IncomingSms.java & BroadcastNewSms.java. Code: IncomingSms.java
package com.example.broadcastreceivernewsms;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
//Uri uri = Uri.parse("content://sms");
//String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
//Cursor cursor = getContentResolver().query(uri, projection, "address='51555'", null, "date desc");
// Retrieves a map of extended data from the intent.
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();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
Code:BroadcastNewSms.java
public class BroadcastNewSms extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_new_sms);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_broadcast_new_sms, menu);
return true;
}
}
It works fine.When I run the app & whenever a new sms comes into my device it prints the sender number & messagebody into the Toast. Now my question is that,how can I create a message in Notification bar that "A New message received"(Like whenever we receive a sms in Whatsapp it prints give a notification in notificatiobar,if the app is not running directly) whenever a new message received into my device.