LocalNotification.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
  3. *
  4. * @APPPLANT_LICENSE_HEADER_START@
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apache License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://opensource.org/licenses/Apache-2.0/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. *
  21. * @APPPLANT_LICENSE_HEADER_END@
  22. */
  23. package de.appplant.cordova.plugin.localnotification;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import org.apache.cordova.CallbackContext;
  27. import org.apache.cordova.CordovaPlugin;
  28. import org.apache.cordova.CordovaWebView;
  29. import org.apache.cordova.PluginResult;
  30. import org.json.JSONArray;
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33. import android.os.Build;
  34. import de.appplant.cordova.plugin.notification.*;
  35. /**
  36. * This plugin utilizes the Android AlarmManager in combination with local
  37. * notifications. When a local notification is scheduled the alarm manager takes
  38. * care of firing the event. When the event is processed, a notification is put
  39. * in the Android notification center and status bar.
  40. */
  41. public class LocalNotification extends CordovaPlugin {
  42. // Reference to the web view for static access
  43. private static CordovaWebView webView = null;
  44. // Indicates if the device is ready (to receive events)
  45. private static Boolean deviceready = false;
  46. // To inform the user about the state of the app in callbacks
  47. protected static Boolean isInBackground = true;
  48. // Queues all events before deviceready
  49. private static ArrayList<String> eventQueue = new ArrayList<String>();
  50. /**
  51. * Called after plugin construction and fields have been initialized.
  52. */
  53. @Override
  54. protected void pluginInitialize() {
  55. LocalNotification.webView = super.webView;
  56. }
  57. /**
  58. * Called when the system is about to start resuming a previous activity.
  59. *
  60. * @param multitasking
  61. * Flag indicating if multitasking is turned on for app
  62. */
  63. @Override
  64. public void onPause(boolean multitasking) {
  65. super.onPause(multitasking);
  66. isInBackground = true;
  67. }
  68. /**
  69. * Called when the activity will start interacting with the user.
  70. *
  71. * @param multitasking
  72. * Flag indicating if multitasking is turned on for app
  73. */
  74. @Override
  75. public void onResume(boolean multitasking) {
  76. super.onResume(multitasking);
  77. isInBackground = false;
  78. }
  79. /**
  80. * Executes the request.
  81. *
  82. * This method is called from the WebView thread. To do a non-trivial
  83. * amount of work, use:
  84. * cordova.getThreadPool().execute(runnable);
  85. *
  86. * To run on the UI thread, use:
  87. * cordova.getActivity().runOnUiThread(runnable);
  88. *
  89. * @param action
  90. * The action to execute.
  91. * @param args
  92. * The exec() arguments in JSON form.
  93. * @param command
  94. * The callback context used when calling back into JavaScript.
  95. * @return
  96. * Whether the action was valid.
  97. */
  98. @Override
  99. public boolean execute (final String action, final JSONArray args,
  100. final CallbackContext command) throws JSONException {
  101. Notification.setDefaultTriggerReceiver(TriggerReceiver.class);
  102. cordova.getThreadPool().execute(new Runnable() {
  103. public void run() {
  104. if (action.equals("schedule")) {
  105. schedule(args);
  106. command.success();
  107. }
  108. else if (action.equals("update")) {
  109. update(args);
  110. command.success();
  111. }
  112. else if (action.equals("cancel")) {
  113. cancel(args);
  114. command.success();
  115. }
  116. else if (action.equals("cancelAll")) {
  117. cancelAll();
  118. command.success();
  119. }
  120. else if (action.equals("clear")) {
  121. clear(args);
  122. command.success();
  123. }
  124. else if (action.equals("clearAll")) {
  125. clearAll();
  126. command.success();
  127. }
  128. else if (action.equals("isPresent")) {
  129. isPresent(args.optInt(0), command);
  130. }
  131. else if (action.equals("isScheduled")) {
  132. isScheduled(args.optInt(0), command);
  133. }
  134. else if (action.equals("isTriggered")) {
  135. isTriggered(args.optInt(0), command);
  136. }
  137. else if (action.equals("getAllIds")) {
  138. getAllIds(command);
  139. }
  140. else if (action.equals("getScheduledIds")) {
  141. getScheduledIds(command);
  142. }
  143. else if (action.equals("getTriggeredIds")) {
  144. getTriggeredIds(command);
  145. }
  146. else if (action.equals("getAll")) {
  147. getAll(args, command);
  148. }
  149. else if (action.equals("getScheduled")) {
  150. getScheduled(args, command);
  151. }
  152. else if (action.equals("getTriggered")) {
  153. getTriggered(args, command);
  154. }
  155. else if (action.equals("deviceready")) {
  156. deviceready();
  157. }
  158. }
  159. });
  160. return true;
  161. }
  162. /**
  163. * Schedule multiple local notifications.
  164. *
  165. * @param notifications
  166. * Properties for each local notification
  167. */
  168. private void schedule (JSONArray notifications) {
  169. for (int i = 0; i < notifications.length(); i++) {
  170. JSONObject options = notifications.optJSONObject(i);
  171. Notification notification =
  172. getNotificationMgr().schedule(options, TriggerReceiver.class);
  173. fireEvent("schedule", notification);
  174. }
  175. }
  176. /**
  177. * Update multiple local notifications.
  178. *
  179. * @param updates
  180. * Notification properties including their IDs
  181. */
  182. private void update (JSONArray updates) {
  183. for (int i = 0; i < updates.length(); i++) {
  184. JSONObject update = updates.optJSONObject(i);
  185. int id = update.optInt("id", 0);
  186. Notification notification =
  187. getNotificationMgr().update(id, update, TriggerReceiver.class);
  188. fireEvent("update", notification);
  189. }
  190. }
  191. /**
  192. * Cancel multiple local notifications.
  193. *
  194. * @param ids
  195. * Set of local notification IDs
  196. */
  197. private void cancel (JSONArray ids) {
  198. for (int i = 0; i < ids.length(); i++) {
  199. int id = ids.optInt(i, 0);
  200. Notification notification =
  201. getNotificationMgr().cancel(id);
  202. fireEvent("cancel", notification);
  203. }
  204. }
  205. /**
  206. * Cancel all scheduled notifications.
  207. */
  208. private void cancelAll() {
  209. getNotificationMgr().cancelAll();
  210. fireEvent("cancelall");
  211. }
  212. /**
  213. * Clear multiple local notifications without canceling them.
  214. *
  215. * @param ids
  216. * Set of local notification IDs
  217. */
  218. private void clear(JSONArray ids){
  219. for (int i = 0; i < ids.length(); i++) {
  220. int id = ids.optInt(i, 0);
  221. Notification notification =
  222. getNotificationMgr().clear(id);
  223. fireEvent("clear", notification);
  224. }
  225. }
  226. /**
  227. * Clear all triggered notifications without canceling them.
  228. */
  229. private void clearAll() {
  230. getNotificationMgr().clearAll();
  231. fireEvent("clearall");
  232. }
  233. /**
  234. * If a notification with an ID is present.
  235. *
  236. * @param id
  237. * Notification ID
  238. * @param command
  239. * The callback context used when calling back into JavaScript.
  240. */
  241. private void isPresent (int id, CallbackContext command) {
  242. boolean exist = getNotificationMgr().exist(id);
  243. PluginResult result = new PluginResult(
  244. PluginResult.Status.OK, exist);
  245. command.sendPluginResult(result);
  246. }
  247. /**
  248. * If a notification with an ID is scheduled.
  249. *
  250. * @param id
  251. * Notification ID
  252. * @param command
  253. * The callback context used when calling back into JavaScript.
  254. */
  255. private void isScheduled (int id, CallbackContext command) {
  256. boolean exist = getNotificationMgr().exist(
  257. id, Notification.Type.SCHEDULED);
  258. PluginResult result = new PluginResult(
  259. PluginResult.Status.OK, exist);
  260. command.sendPluginResult(result);
  261. }
  262. /**
  263. * If a notification with an ID is triggered.
  264. *
  265. * @param id
  266. * Notification ID
  267. * @param command
  268. * The callback context used when calling back into JavaScript.
  269. */
  270. private void isTriggered (int id, CallbackContext command) {
  271. boolean exist = getNotificationMgr().exist(
  272. id, Notification.Type.TRIGGERED);
  273. PluginResult result = new PluginResult(
  274. PluginResult.Status.OK, exist);
  275. command.sendPluginResult(result);
  276. }
  277. /**
  278. * Set of IDs from all existent notifications.
  279. *
  280. * @param command
  281. * The callback context used when calling back into JavaScript.
  282. */
  283. private void getAllIds (CallbackContext command) {
  284. List<Integer> ids = getNotificationMgr().getIds();
  285. command.success(new JSONArray(ids));
  286. }
  287. /**
  288. * Set of IDs from all scheduled notifications.
  289. *
  290. * @param command
  291. * The callback context used when calling back into JavaScript.
  292. */
  293. private void getScheduledIds (CallbackContext command) {
  294. List<Integer> ids = getNotificationMgr().getIdsByType(
  295. Notification.Type.SCHEDULED);
  296. command.success(new JSONArray(ids));
  297. }
  298. /**
  299. * Set of IDs from all triggered notifications.
  300. *
  301. * @param command
  302. * The callback context used when calling back into JavaScript.
  303. */
  304. private void getTriggeredIds (CallbackContext command) {
  305. List<Integer> ids = getNotificationMgr().getIdsByType(
  306. Notification.Type.TRIGGERED);
  307. command.success(new JSONArray(ids));
  308. }
  309. /**
  310. * Set of options from local notification.
  311. *
  312. * @param ids
  313. * Set of local notification IDs
  314. * @param command
  315. * The callback context used when calling back into JavaScript.
  316. */
  317. private void getAll (JSONArray ids, CallbackContext command) {
  318. List<JSONObject> options;
  319. if (ids.length() == 0) {
  320. options = getNotificationMgr().getOptions();
  321. } else {
  322. options = getNotificationMgr().getOptionsById(toList(ids));
  323. }
  324. command.success(new JSONArray(options));
  325. }
  326. /**
  327. * Set of options from scheduled notifications.
  328. *
  329. * @param ids
  330. * Set of local notification IDs
  331. * @param command
  332. * The callback context used when calling back into JavaScript.
  333. */
  334. private void getScheduled (JSONArray ids, CallbackContext command) {
  335. List<JSONObject> options;
  336. if (ids.length() == 0) {
  337. options = getNotificationMgr().getOptionsByType(Notification.Type.SCHEDULED);
  338. } else {
  339. options = getNotificationMgr().getOptionsBy(
  340. Notification.Type.SCHEDULED, toList(ids));
  341. }
  342. command.success(new JSONArray(options));
  343. }
  344. /**
  345. * Set of options from triggered notifications.
  346. *
  347. * @param ids
  348. * Set of local notification IDs
  349. * @param command
  350. * The callback context used when calling back into JavaScript.
  351. */
  352. private void getTriggered (JSONArray ids, CallbackContext command) {
  353. List<JSONObject> options;
  354. if (ids.length() == 0) {
  355. options = getNotificationMgr().getOptionsByType(Notification.Type.TRIGGERED);
  356. } else {
  357. options = getNotificationMgr().getOptionsBy(
  358. Notification.Type.TRIGGERED, toList(ids));
  359. }
  360. command.success(new JSONArray(options));
  361. }
  362. /**
  363. * Call all pending callbacks after the deviceready event has been fired.
  364. */
  365. private static synchronized void deviceready () {
  366. isInBackground = false;
  367. deviceready = true;
  368. for (String js : eventQueue) {
  369. sendJavascript(js);
  370. }
  371. eventQueue.clear();
  372. }
  373. /**
  374. * Fire given event on JS side. Does inform all event listeners.
  375. *
  376. * @param event
  377. * The event name
  378. */
  379. private void fireEvent (String event) {
  380. fireEvent(event, null);
  381. }
  382. /**
  383. * Fire given event on JS side. Does inform all event listeners.
  384. *
  385. * @param event
  386. * The event name
  387. * @param notification
  388. * Optional local notification to pass the id and properties.
  389. */
  390. static void fireEvent (String event, Notification notification) {
  391. String state = getApplicationState();
  392. String params = "\"" + state + "\"";
  393. if (notification != null) {
  394. params = notification.toString() + "," + params;
  395. }
  396. String js = "cordova.plugins.notification.local.fireEvent(" +
  397. "\"" + event + "\"," + params + ")";
  398. sendJavascript(js);
  399. }
  400. /**
  401. * Use this instead of deprecated sendJavascript
  402. *
  403. * @param js
  404. * JS code snippet as string
  405. */
  406. private static synchronized void sendJavascript(final String js) {
  407. if (!deviceready) {
  408. eventQueue.add(js);
  409. return;
  410. }
  411. webView.post(new Runnable(){
  412. public void run(){
  413. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  414. webView.evaluateJavascript(js, null);
  415. } else {
  416. webView.loadUrl("javascript:" + js);
  417. }
  418. }
  419. });
  420. }
  421. /**
  422. * Convert JSON array of integers to List.
  423. *
  424. * @param ary
  425. * Array of integers
  426. */
  427. private List<Integer> toList (JSONArray ary) {
  428. ArrayList<Integer> list = new ArrayList<Integer>();
  429. for (int i = 0; i < ary.length(); i++) {
  430. list.add(ary.optInt(i));
  431. }
  432. return list;
  433. }
  434. /**
  435. * Current application state.
  436. *
  437. * @return
  438. * "background" or "foreground"
  439. */
  440. static String getApplicationState () {
  441. return isInBackground ? "background" : "foreground";
  442. }
  443. /**
  444. * Notification manager instance.
  445. */
  446. private Manager getNotificationMgr() {
  447. return Manager.getInstance(cordova.getActivity());
  448. }
  449. }