Saturday, June 15, 2013

Generate Notification with sound when alarm received

The exercise "Set alarm on specified date/time with DatePicker/TimePicker" simple display Toast when alarm time reached. To generate Notification with sound when alarm received, generate Notification in AlarmReceiver.java using Notification.Builder() or NotificationCompat.Builder().

This exercise use Android Support library's NotificationCompat.Builder() to supports Android version as old as API level 4. (Right click your project > Android Tools > Add Sipport Library...)

Generate Notification with sound when alarm received


Modify AlarmReceiver.java
package com.example.androiddatepicker;

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.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);

myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Exercise of Notification!")
.setContentText("http://android-er.blogspot.com/")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();

notificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}

}


download filesDownload the files.

Next:
- Start activity once notification clicked


No comments:

Post a Comment