Parcourir la source

Merged AlarmHelper into LocalNotification

Sebastián Katzer il y a 12 ans
Parent
commit
52aa742aca

+ 1 - 2
plugin.xml

@@ -44,8 +44,7 @@
         </config-file>
 
         <source-file src="src/android/AlarmReceiver.java" target-dir="src/de/appplant/cordova/plugin" />
-        <source-file src="src/android/AlarmHelper.java" target-dir="src/de/appplant/cordova/plugin" />
-        <source-file src="src/android/AlarmOptions.java" target-dir="src/de/appplant/cordova/plugin" />
+        <source-file src="src/android/LocalNotificationOptions.java" target-dir="src/de/appplant/cordova/plugin" />
         <source-file src="src/android/AlarmRestoreOnBoot.java" target-dir="src/de/appplant/cordova/plugin" />
         <source-file src="src/android/LocalNotification.java" target-dir="src/de/appplant/cordova/plugin" />
 

+ 0 - 109
src/android/AlarmHelper.java

@@ -1,109 +0,0 @@
-package de.appplant.cordova.plugin;
-
-import java.util.Calendar;
-import java.util.Map;
-import java.util.Set;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.util.Log;
-
-/**
- * Helper class for the LocalNotification plugin. This class is reused by the
- * AlarmRestoreOnBoot.
- *
- * @see LocalNotification
- * @see AlarmRestoreOnBoot
- *
- * @author dvtoever
- */
-public class AlarmHelper {
-
-    private Context ctx;
-
-    public AlarmHelper(Context context) {
-	this.ctx = context;
-    }
-
-    /**
-     * @see LocalNotification#add(boolean, String, String, String, int,
-     *      Calendar)
-     */
-    public boolean addAlarm(boolean repeatDaily, String alarmTitle, String alarmSubTitle, String alarmTicker,
-	    String notificationId, Calendar cal) {
-
-	final long triggerTime = cal.getTimeInMillis();
-	final Intent intent = new Intent(this.ctx, AlarmReceiver.class);
-	final int hour = cal.get(Calendar.HOUR_OF_DAY);
-	final int min = cal.get(Calendar.MINUTE);
-
-	intent.setAction("" + notificationId);
-	intent.putExtra(AlarmReceiver.TITLE, alarmTitle);
-	intent.putExtra(AlarmReceiver.SUBTITLE, alarmSubTitle);
-	intent.putExtra(AlarmReceiver.TICKER_TEXT, alarmTicker);
-	intent.putExtra(AlarmReceiver.NOTIFICATION_ID, notificationId);
-	intent.putExtra(AlarmReceiver.HOUR_OF_DAY, hour);
-	intent.putExtra(AlarmReceiver.MINUTE, min);
-
-	final PendingIntent sender = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
-	/* Get the AlarmManager service */
-	final AlarmManager am = getAlarmManager();
-
-	if (repeatDaily) {
-	    am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, AlarmManager.INTERVAL_DAY, sender);
-	} else {
-	    am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
-	}
-
-	return true;
-    }
-
-    /**
-     * @see LocalNotification#cancelNotification(int)
-     */
-    public boolean cancelAlarm(String notificationId) {
-	/*
-	 * Create an intent that looks similar, to the one that was registered
-	 * using add. Making sure the notification id in the action is the same.
-	 * Now we can search for such an intent using the 'getService' method
-	 * and cancel it.
-	 */
-	final Intent intent = new Intent(this.ctx, AlarmReceiver.class);
-	intent.setAction("" + notificationId);
-
-	final PendingIntent pi = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
-	final AlarmManager am = getAlarmManager();
-
-	try {
-	    am.cancel(pi);
-	} catch (Exception e) {
-	    return false;
-	}
-	return true;
-    }
-
-    /**
-     * @see LocalNotification#cancelAllNotifications()
-     */
-    public boolean cancelAll(SharedPreferences alarmSettings) {
-	final Map<String, ?> allAlarms = alarmSettings.getAll();
-	final Set<String> alarmIds = allAlarms.keySet();
-
-	for (String alarmId : alarmIds) {
-	    Log.d(LocalNotification.PLUGIN_NAME, "Canceling notification with id: " + alarmId);
-	    String alarmInt = alarmId;
-	    cancelAlarm(alarmInt);
-	}
-
-	return true;
-    }
-
-    private AlarmManager getAlarmManager() {
-	final AlarmManager am = (AlarmManager) this.ctx.getSystemService(Context.ALARM_SERVICE);
-
-	return am;
-    }
-}

+ 0 - 111
src/android/AlarmOptions.java

@@ -1,111 +0,0 @@
-package de.appplant.cordova.plugin;
-
-import java.util.Calendar;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-
-/**
- * Class that helps to store the options that can be specified per alarm.
- *
- * @author dvtoever
- */
-public class AlarmOptions {
-
-    /*
-     * Options that can be set when this plugin is invoked
-     */
-    private Calendar cal = Calendar.getInstance();
-    private String alarmTitle = "";
-    private String alarmSubTitle = "";
-    private String alarmTicker = "";
-    private boolean repeatDaily = false;
-    private String notificationId = "";
-
-    /**
-     * Parse options passed from javascript part of this plugin.
-     *
-     * @param optionsArr
-     *            JSON Array containing the list options.
-     */
-    public void parseOptions(JSONArray optionsArr) {
-	final JSONObject options = optionsArr.optJSONObject(0);
-
-	if (options != null) {
-
-	    // Parse string representing the date
-	    String textDate = options.optString("date");
-	    if (!"".equals(textDate)) {
-		String[] datePart = textDate.split("/");
-		int month = Integer.parseInt(datePart[0]);
-		int day = Integer.parseInt(datePart[1]);
-		int year = Integer.parseInt(datePart[2]);
-		int hour = Integer.parseInt(datePart[3]);
-		int min = Integer.parseInt(datePart[4]);
-
-		cal.set(year, month, day, hour, min);
-	    }
-
-	    String optString = options.optString("message");
-	    if (!"".equals(optString)) {
-		String lines[] = optString.split("\\r?\\n");
-		alarmTitle = lines[0];
-		if (lines.length > 1)
-		    alarmSubTitle = lines[1];
-	    }
-
-	    alarmTicker = options.optString("ticker");
-	    repeatDaily = options.optBoolean("repeatDaily");
-	    notificationId = options.optString("id");
-	}
-    }
-
-    public Calendar getCal() {
-	return cal;
-    }
-
-    public void setCal(Calendar cal) {
-	this.cal = cal;
-    }
-
-    public String getAlarmTitle() {
-	return alarmTitle;
-    }
-
-    public void setAlarmTitle(String alarmTitle) {
-	this.alarmTitle = alarmTitle;
-    }
-
-    public String getAlarmSubTitle() {
-	return alarmSubTitle;
-    }
-
-    public void setAlarmSubTitle(String alarmSubTitle) {
-	this.alarmSubTitle = alarmSubTitle;
-    }
-
-    public String getAlarmTicker() {
-	return alarmTicker;
-    }
-
-    public void setAlarmTicker(String alarmTicker) {
-	this.alarmTicker = alarmTicker;
-    }
-
-    public boolean isRepeatDaily() {
-	return repeatDaily;
-    }
-
-    public void setRepeatDaily(boolean repeatDaily) {
-	this.repeatDaily = repeatDaily;
-    }
-
-    public String getNotificationId() {
-	return notificationId;
-    }
-
-    public void setNotificationId(String notificationId) {
-	this.notificationId = notificationId;
-    }
-
-}

+ 66 - 36
src/android/LocalNotification.java

@@ -9,11 +9,18 @@
 
 package de.appplant.cordova.plugin;
 
+import java.util.Calendar;
+import java.util.Map;
+import java.util.Set;
+
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 
+import android.content.Intent;
 import android.content.Context;
+import android.app.AlarmManager;
+import android.app.PendingIntent;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 
@@ -30,12 +37,6 @@ public class LocalNotification extends CordovaPlugin {
 
     public static final String PLUGIN_NAME = "LocalNotification";
 
-    /**
-     * Delegate object that does the actual alarm registration. Is reused by the
-     * AlarmRestoreOnBoot class.
-     */
-    private AlarmHelper alarm = null;
-
     @Override
     public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
         JSONObject arguments             = args.getJSONObject(0);
@@ -45,8 +46,6 @@ public class LocalNotification extends CordovaPlugin {
 
         String alarmId = options.getNotificationId();
 
-        alarm = new AlarmHelper(cordova.getActivity());
-
         if (action.equalsIgnoreCase("add")) {
             persist(alarmId, args);
             add(options);
@@ -76,21 +75,34 @@ public class LocalNotification extends CordovaPlugin {
     /**
      * Set an alarm
      *
-     * @param repeatDaily
-     *            If true, the alarm interval will be set to one day.
-     * @param title
-     *            The title of the alarm as shown in the Android notification
-     *            panel
-     * @param subTitle
-     *            The subtitle of the alarm
-     * @param alarmId
-     *            The unique ID of the notification
-     * @param calender
-     *            A calendar object that represents the time at which the alarm
-     *            should first be started
+     * @param options
+     *            The options that can be specified per alarm.
      */
     public void add(LocalNotificationOptions options) {
-        alarm.add(options);
+        Calendar calendar = options.getCalendar();
+        long triggerTime  = calendar.getTimeInMillis();
+        int hour          = calendar.get(Calendar.HOUR_OF_DAY);
+        int min           = calendar.get(Calendar.MINUTE);
+
+        Intent intent     = new Intent(cordova.getActivity(), AlarmReceiver.class);
+
+        intent.setAction("" + options.getNotificationId());
+        intent.putExtra(AlarmReceiver.TITLE, options.getTitle());
+        intent.putExtra(AlarmReceiver.SUBTITLE, options.getSubTitle());
+        intent.putExtra(AlarmReceiver.TICKER_TEXT, options.getTicker());
+        intent.putExtra(AlarmReceiver.NOTIFICATION_ID, options.getNotificationId());
+        intent.putExtra(AlarmReceiver.HOUR_OF_DAY, hour);
+        intent.putExtra(AlarmReceiver.MINUTE, min);
+
+        PendingIntent sender = PendingIntent.getBroadcast(cordova.getActivity(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
+        /* Get the AlarmManager service */
+        AlarmManager am      = getAlarmManager();
+
+        if (options.isRepeatDaily()) {
+            am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, AlarmManager.INTERVAL_DAY, sender);
+        } else {
+            am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
+        }
     }
 
     /**
@@ -101,22 +113,40 @@ public class LocalNotification extends CordovaPlugin {
      *            registered using add()
      */
     public void cancel (String notificationId) {
-        alarm.cancel(notificationId);
+        /*
+         * Create an intent that looks similar, to the one that was registered
+         * using add. Making sure the notification id in the action is the same.
+         * Now we can search for such an intent using the 'getService' method
+         * and cancel it.
+         */
+        Intent intent = new Intent(cordova.getActivity(), AlarmReceiver.class);
+
+        intent.setAction("" + notificationId);
+
+        PendingIntent pi = PendingIntent.getBroadcast(cordova.getActivity(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
+        AlarmManager am  = getAlarmManager();
+
+        try {
+            am.cancel(pi);
+        } catch (Exception e) {}
     }
 
     /**
      * Cancel all notifications that were created by this plugin.
+     *
+     * Android can only unregister a specific alarm. There is no such thing
+     * as cancelAll. Therefore we rely on the Shared Preferences which holds
+     * all our alarms to loop through these alarms and unregister them one
+     * by one.
      */
     public void cancelAll() {
-        /*
-         * Android can only unregister a specific alarm. There is no such thing
-         * as cancelAll. Therefore we rely on the Shared Preferences which holds
-         * all our alarms to loop through these alarms and unregister them one
-         * by one.
-         */
         SharedPreferences settings = cordova.getActivity().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE);
+        Map<String, ?> alarms      = settings.getAll();
+        Set<String> alarmIds       = alarms.keySet();
 
-        alarm.cancelAll(settings);
+        for (String alarmId : alarmIds) {
+            cancel(alarmId);
+        }
     }
 
     /**
@@ -124,17 +154,13 @@ public class LocalNotification extends CordovaPlugin {
      * This will allow the application to restore the alarm upon device reboot.
      * Also this is used by the cancelAll method.
      *
-     * @see #cancelAllNotifications()
-     *
-     * @param optionsArr
+     * @param args
      *            The assumption is that parse has been called already.
-     *
-     * @return true when successfull, otherwise false
      */
-    private void persist (String alarmId, JSONArray optionsArr) {
+    private void persist (String alarmId, JSONArray args) {
         Editor editor = cordova.getActivity().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE).edit();
 
-        editor.putString(alarmId, optionsArr.toString());
+        editor.putString(alarmId, args.toString());
         editor.commit();
     }
 
@@ -160,4 +186,8 @@ public class LocalNotification extends CordovaPlugin {
         editor.clear();
         editor.commit();
     }
+
+    private AlarmManager getAlarmManager () {
+        return (AlarmManager) cordova.getActivity().getSystemService(Context.ALARM_SERVICE);
+    }
 }

+ 4 - 4
src/android/LocalNotificationOptions.java

@@ -21,7 +21,7 @@ public class LocalNotificationOptions {
     /*
      * Options that can be set when this plugin is invoked
      */
-    private Calendar calender     = Calendar.getInstance();
+    private Calendar calendar     = Calendar.getInstance();
     private String title          = "";
     private String subTitle       = "";
     private String ticker         = "";
@@ -45,7 +45,7 @@ public class LocalNotificationOptions {
             int hour  = Integer.parseInt(dateParts[3]);
             int min   = Integer.parseInt(dateParts[4]);
 
-    		calender.set(year, month, day, hour, min);
+    		calendar.set(year, month, day, hour, min);
 	    }
 
 	    if (!"".equals(message)) {
@@ -65,8 +65,8 @@ public class LocalNotificationOptions {
     /**
      * Gibt den Kalender mit dem Datum der nächsten Notification an.
      */
-    public Calendar getCalender() {
-	   return calender;
+    public Calendar getCalendar() {
+	   return calendar;
     }
 
     /**