LocalNotification.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. Copyright 2013-2014 appPlant UG
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing,
  12. software distributed under the License is distributed on an
  13. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. KIND, either express or implied. See the License for the
  15. specific language governing permissions and limitations
  16. under the License.
  17. */
  18. package de.appplant.cordova.plugin.localnotification;
  19. import java.util.ArrayList;
  20. import java.util.Map;
  21. import java.util.Set;
  22. import org.apache.cordova.CallbackContext;
  23. import org.apache.cordova.CordovaInterface;
  24. import org.apache.cordova.CordovaPlugin;
  25. import org.apache.cordova.CordovaWebView;
  26. import org.apache.cordova.PluginResult;
  27. import org.json.JSONArray;
  28. import org.json.JSONException;
  29. import org.json.JSONObject;
  30. import android.app.ActivityManager;
  31. import android.app.AlarmManager;
  32. import android.app.NotificationManager;
  33. import android.app.PendingIntent;
  34. import android.content.Context;
  35. import android.content.Intent;
  36. import android.content.SharedPreferences;
  37. import android.content.SharedPreferences.Editor;
  38. /**
  39. * This plugin utilizes the Android AlarmManager in combination with StatusBar
  40. * notifications. When a local notification is scheduled the alarm manager takes
  41. * care of firing the event. When the event is processed, a notification is put
  42. * in the Android status bar.
  43. */
  44. public class LocalNotification extends CordovaPlugin {
  45. protected final static String PLUGIN_NAME = "LocalNotification";
  46. private static CordovaWebView webView = null;
  47. protected static Context context = null;
  48. private static ArrayList<String> callbackQueue = new ArrayList<String>();
  49. @Override
  50. public void initialize (CordovaInterface cordova, CordovaWebView webView) {
  51. super.initialize(cordova, webView);
  52. LocalNotification.webView = super.webView;
  53. LocalNotification.context = super.cordova.getActivity().getApplicationContext();
  54. execPendingCallbacks();
  55. }
  56. @Override
  57. public boolean execute (String action, final JSONArray args, CallbackContext callbackContext) throws JSONException {
  58. if (action.equalsIgnoreCase("add")) {
  59. cordova.getThreadPool().execute( new Runnable() {
  60. public void run() {
  61. JSONObject arguments = args.optJSONObject(0);
  62. Options options = new Options(context).parse(arguments);
  63. persist(options.getId(), args);
  64. add(options, true);
  65. }
  66. });
  67. return true;
  68. }
  69. if (action.equalsIgnoreCase("cancel")) {
  70. cordova.getThreadPool().execute( new Runnable() {
  71. public void run() {
  72. String id = args.optString(0);
  73. cancel(id);
  74. unpersist(id);
  75. }
  76. });
  77. return true;
  78. }
  79. if (action.equalsIgnoreCase("cancelAll")) {
  80. cordova.getThreadPool().execute( new Runnable() {
  81. public void run() {
  82. cancelAll();
  83. unpersistAll();
  84. }
  85. });
  86. return true;
  87. }
  88. if (action.equalsIgnoreCase("isScheduled")) {
  89. String id = args.optString(0);
  90. isScheduled(id, callbackContext);
  91. return true;
  92. }
  93. if (action.equalsIgnoreCase("getScheduledIds")) {
  94. getScheduledIds(callbackContext);
  95. return true;
  96. }
  97. // Returning false results in a "MethodNotFound" error.
  98. return false;
  99. }
  100. /**
  101. * Set an alarm.
  102. *
  103. * @param options
  104. * The options that can be specified per alarm.
  105. * @param doFireEvent
  106. * If the onadd callback shall be called.
  107. */
  108. public static void add (Options options, boolean doFireEvent) {
  109. long triggerTime = options.getDate();
  110. Intent intent = new Intent(context, Receiver.class)
  111. .setAction("" + options.getId())
  112. .putExtra(Receiver.OPTIONS, options.getJSONObject().toString());
  113. AlarmManager am = getAlarmManager();
  114. PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  115. if (doFireEvent) {
  116. fireEvent("add", options.getId(), options.getJSON());
  117. }
  118. am.set(AlarmManager.RTC_WAKEUP, triggerTime, pi);
  119. }
  120. /**
  121. * Cancel a specific notification that was previously registered.
  122. *
  123. * @param notificationId
  124. * The original ID of the notification that was used when it was
  125. * registered using add()
  126. */
  127. public static void cancel (String notificationId) {
  128. /*
  129. * Create an intent that looks similar, to the one that was registered
  130. * using add. Making sure the notification id in the action is the same.
  131. * Now we can search for such an intent using the 'getService' method
  132. * and cancel it.
  133. */
  134. Intent intent = new Intent(context, Receiver.class)
  135. .setAction("" + notificationId);
  136. PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  137. AlarmManager am = getAlarmManager();
  138. NotificationManager nc = getNotificationManager();
  139. am.cancel(pi);
  140. try {
  141. nc.cancel(Integer.parseInt(notificationId));
  142. } catch (Exception e) {}
  143. fireEvent("cancel", notificationId, "");
  144. }
  145. /**
  146. * Cancel all notifications that were created by this plugin.
  147. *
  148. * Android can only unregister a specific alarm. There is no such thing
  149. * as cancelAll. Therefore we rely on the Shared Preferences which holds
  150. * all our alarms to loop through these alarms and unregister them one
  151. * by one.
  152. */
  153. public static void cancelAll() {
  154. SharedPreferences settings = getSharedPreferences();
  155. NotificationManager nc = getNotificationManager();
  156. Map<String, ?> alarms = settings.getAll();
  157. Set<String> alarmIds = alarms.keySet();
  158. for (String alarmId : alarmIds) {
  159. cancel(alarmId);
  160. }
  161. nc.cancelAll();
  162. }
  163. /**
  164. * Checks wether a notification with an ID is scheduled.
  165. *
  166. * @param id
  167. * The notification ID to be check.
  168. * @param callbackContext
  169. */
  170. public static void isScheduled (String id, CallbackContext callbackContext) {
  171. SharedPreferences settings = getSharedPreferences();
  172. Map<String, ?> alarms = settings.getAll();
  173. boolean isScheduled = alarms.containsKey(id);
  174. PluginResult result = new PluginResult(PluginResult.Status.OK, isScheduled);
  175. callbackContext.sendPluginResult(result);
  176. }
  177. /**
  178. * Retrieves a list with all currently pending notifications.
  179. *
  180. * @param callbackContext
  181. */
  182. public static void getScheduledIds (CallbackContext callbackContext) {
  183. SharedPreferences settings = getSharedPreferences();
  184. Map<String, ?> alarms = settings.getAll();
  185. Set<String> alarmIds = alarms.keySet();
  186. JSONArray pendingIds = new JSONArray(alarmIds);
  187. callbackContext.success(pendingIds);
  188. }
  189. /**
  190. * Persist the information of this alarm to the Android Shared Preferences.
  191. * This will allow the application to restore the alarm upon device reboot.
  192. * Also this is used by the cancelAll method.
  193. *
  194. * @param alarmId
  195. * The Id of the notification that must be persisted.
  196. * @param args
  197. * The assumption is that parse has been called already.
  198. */
  199. public static void persist (String alarmId, JSONArray args) {
  200. Editor editor = getSharedPreferences().edit();
  201. if (alarmId != null) {
  202. editor.putString(alarmId, args.toString());
  203. editor.apply();
  204. }
  205. }
  206. /**
  207. * Remove a specific alarm from the Android shared Preferences.
  208. *
  209. * @param alarmId
  210. * The Id of the notification that must be removed.
  211. */
  212. public static void unpersist (String alarmId) {
  213. Editor editor = getSharedPreferences().edit();
  214. if (alarmId != null) {
  215. editor.remove(alarmId);
  216. editor.apply();
  217. }
  218. }
  219. /**
  220. * Clear all alarms from the Android shared Preferences.
  221. */
  222. public static void unpersistAll () {
  223. Editor editor = getSharedPreferences().edit();
  224. editor.clear();
  225. editor.apply();
  226. }
  227. /**
  228. * Fires the given event.
  229. *
  230. * @param {String} event The Name of the event
  231. * @param {String} id The ID of the notification
  232. * @param {String} json A custom (JSON) string
  233. */
  234. public static void fireEvent (String event, String id, String json) {
  235. String state = isInBackground() ? "background" : "foreground";
  236. String params = "\"" + id + "\",\"" + state + "\",\\'" + JSONObject.quote(json) + "\\'.replace(/(^\"|\"$)/g, \\'\\')";
  237. String js = "setTimeout('plugin.notification.local.on" + event + "(" + params + ")',0)";
  238. // after reboot, LocalNotification.webView is always be null
  239. // call background callback later
  240. if (webView == null) {
  241. callbackQueue.add(js);
  242. } else {
  243. webView.sendJavascript(js);
  244. }
  245. }
  246. /**
  247. * Set the application context if not already set.
  248. */
  249. protected static void setContext (Context context) {
  250. if (LocalNotification.context == null) {
  251. LocalNotification.context = context;
  252. }
  253. }
  254. /**
  255. * The Local storage for the application.
  256. */
  257. protected static SharedPreferences getSharedPreferences () {
  258. return context.getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE);
  259. }
  260. /**
  261. * The alarm manager for the application.
  262. */
  263. protected static AlarmManager getAlarmManager () {
  264. return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  265. }
  266. /**
  267. * The notification manager for the application.
  268. */
  269. protected static NotificationManager getNotificationManager () {
  270. return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  271. }
  272. /**
  273. * Gibt an, ob die App im Hintergrund läuft.
  274. */
  275. private static boolean isInBackground () {
  276. try {
  277. return !context.getPackageName().equalsIgnoreCase(((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName());
  278. } catch (Exception e) {
  279. return true;
  280. }
  281. }
  282. /**
  283. * Calls all pending callbacks after the webview was created.
  284. */
  285. private void execPendingCallbacks () {
  286. for (String js : callbackQueue) {
  287. webView.sendJavascript(js);
  288. }
  289. callbackQueue.clear();
  290. }
  291. }