HypoAlarm/HypoAlarm/src/main/java/za/org/treehouse/hypoalarm/PreAlarmNotify.java

70 lines
3.0 KiB
Java

package za.org.treehouse.hypoalarm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
public class PreAlarmNotify extends Service {
public static final int preNotifyID = 2;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// Remove the notification in the notification bar
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(preNotifyID);
Log.d("AlarmNotify", "Pre-notification stopped.");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Log.d("PreAlarmNotify", "Pre-notification started.");
String alarmTimeStr = sharedPref.getString(getString(R.string.AlarmTimePref), null);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_grey);
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= 11) {
final Notification.Builder notification = new Notification.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.preNotificationText))
.setSmallIcon(R.drawable.alarm_notification)
.setLargeIcon(bm)
.setOnlyAlertOnce(true)
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_HIGH);
// Set up dismiss action
Intent cancelAlarmIntent = new Intent(getBaseContext(), CancelAlarmReceiver.class);
PendingIntent cancelAlarmPendingIntent = PendingIntent.getBroadcast(getBaseContext(), MainActivity.CANCEL_ALARM_REQUEST, cancelAlarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// Cancel the grace period if the user clears the notification
notification.setDeleteIntent(cancelAlarmPendingIntent);
// Allow the user to cancel by clicking a "Cancel" button
notification.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.preNotificationCancellation), cancelAlarmPendingIntent);
// Allow the user to cancel by selecting the ContentText or ContentTitle
notification.setContentIntent(cancelAlarmPendingIntent);
nm.cancel(this.preNotifyID);
nm.notify(this.preNotifyID, notification.build());
}
return super.onStartCommand(intent, flags, startId);
}
}