Commit e071e96a by Sebastián Katzer

Update example

parent f0c90580
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.StrictMode;
import android.util.Log;
public class Asset {
private Activity activity;
protected final String STORAGE_FOLDER;
/**
* Constructor of Asset Class. Takes Applications Activity and a foldername for temporary saving.
*
*@param activity Applications Activity
*@param storageFolder foldername for temporary saving.
*/
public Asset(Activity activity,String storageFolder){
this.activity = activity;
this.STORAGE_FOLDER = storageFolder;
}
/**
* Parse given PathStrings to Uris
* @param notification Notifications JSONObject
* @return new Notification JSONObject with additional iconUri and soundUri
*/
public JSONObject parseURIs(JSONObject notification){
//sound
String sound = notification.optString("sound", null);
Uri soundUri = null;
if (sound != null) {
try {
int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class);
soundUri = RingtoneManager.getDefaultUri(soundId);
} catch (Exception e) {
soundUri = getURIfromPath(sound);
}
}
if (soundUri!= null&&soundUri!=Uri.EMPTY){
try{
notification.put("soundUri", soundUri.toString());
} catch (JSONException jse){
jse.printStackTrace();
}
}
//image
String icon = notification.optString("icon", "icon");
Uri iconUri = null;
iconUri = getURIfromPath(icon);
if (iconUri != Uri.EMPTY&&iconUri != null){
try{
notification.put("iconUri", iconUri.toString());
} catch (JSONException jse){
jse.printStackTrace();
}
}
return notification;
}
/**
* The URI for a path.
*
* @param path The given path
*
* @return The URI pointing to the given path
*/
public Uri getURIfromPath(String path){
if (path.startsWith("res:")) {
return getUriForResourcePath(path);
} else if (path.startsWith("file:///")) {
return getUriForAbsolutePath(path);
} else if (path.startsWith("file://")) {
return getUriForAssetPath(path);
} else if (path.startsWith("http")){
return getUriForHTTP(path);
}
return Uri.parse(path);
}
/**
* The URI for a file.
*
* @param path
* The given absolute path
*
* @return The URI pointing to the given path
*/
private Uri getUriForAbsolutePath(String path) {
String absPath = path.replaceFirst("file://", "");
File file = new File(absPath);
if (!file.exists()) {
Log.e("Asset", "File not found: " + file.getAbsolutePath());
return Uri.EMPTY;
}
return Uri.fromFile(file);
}
/**
* The URI for an asset.
*
* @param path
* The given asset path
*
* @return The URI pointing to the given path
*/
private Uri getUriForAssetPath(String path) {
String resPath = path.replaceFirst("file:/", "www");
String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
File file = new File(storage, fileName);
new File(storage).mkdir();
try {
AssetManager assets = activity.getAssets();
FileOutputStream outStream = new FileOutputStream(file);
InputStream inputStream = assets.open(resPath);
copyFile(inputStream, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (Exception e) {
Log.e("Asset", "File not found: assets/" + resPath);
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
* The URI for a resource.
*
* @param path
* The given relative path
*
* @return The URI pointing to the given path
*/
private Uri getUriForResourcePath(String path) {
String resPath = path.replaceFirst("res://", "");
String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = resPath.substring(resPath.lastIndexOf('.'));
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
int resId = getResId(resPath);
File file = new File(storage, resName + extension);
if (resId == 0) {
Log.e("Asset", "File not found: " + resPath);
return Uri.EMPTY;
}
new File(storage).mkdir();
try {
Resources res = activity.getResources();
FileOutputStream outStream = new FileOutputStream(file);
InputStream inputStream = res.openRawResource(resId);
copyFile(inputStream, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (Exception e) {
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
*Get Uri for HTTP Content
* @param path HTTP adress
* @return Uri of the downloaded file
*/
private Uri getUriForHTTP(String path) {
try {
URL url = new URL(path);
String fileName = path.substring(path.lastIndexOf('/') + 1);
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = path.substring(path.lastIndexOf('.'));
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
File file = new File(storage, resName + extension);
new File(storage).mkdir();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
FileOutputStream outStream = new FileOutputStream(file);
copyFile(input, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (MalformedURLException e) {
Log.e("Asset", "Incorrect URL");
e.printStackTrace();
} catch (FileNotFoundException e) {
Log.e("Asset", "Failed to create new File from HTTP Content");
e.printStackTrace();
} catch (IOException e) {
Log.e("Asset", "No Input can be created from http Stream");
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
* Writes an InputStream to an OutputStream
*
* @param in
* The input stream
* @param out
* The output stream
*/
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
/**
* @return The resource ID for the given resource.
*/
private int getResId(String resPath) {
Resources res = activity.getResources();
int resId;
String pkgName = getPackageName();
String dirName = "drawable";
String fileName = resPath;
if (resPath.contains("/")) {
dirName = resPath.substring(0, resPath.lastIndexOf('/'));
fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
}
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
resId = res.getIdentifier(resName, dirName, pkgName);
if (resId == 0) {
resId = res.getIdentifier(resName, "drawable", pkgName);
}
return resId;
}
/**
* The name for the package.
*
* @return The package name
*/
private String getPackageName() {
return activity.getPackageName();
}
}
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
public class NotificationBuilder {
private Options options;
private Context context;
private Builder notification;
private final String OPTIONS;
private Class<?> deleteIntentReceiver;
private Class<?> receiverActivity;
/**
* Constructor of NotificationBuilder
* @param options
* @param context
* @param OPTIONS
* @param deleteIntentReceiver
* @param receiverActivity
*/
public NotificationBuilder(Options options,Context context, String OPTIONS,
Class<?> deleteIntentReceiver, Class<?> receiverActivity){
this.options = options;
this.context = context;
this.OPTIONS = OPTIONS;
this.deleteIntentReceiver = deleteIntentReceiver;
this.receiverActivity = receiverActivity;
}
/**
* Creates the notification.
*/
@SuppressLint("NewApi")
public Builder buildNotification () {
Uri sound = options.getSound();
//DeleteIntent is called when the user clears a notification manually
Intent deleteIntent = new Intent(context, deleteIntentReceiver)
.setAction("" + options.getId())
.putExtra(OPTIONS, options.getJSONObject().toString());
PendingIntent dpi = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification = new NotificationCompat.Builder(context)
.setDefaults(0) // Do not inherit any defaults
.setContentTitle(options.getTitle())
.setContentText(options.getMessage())
.setNumber(options.getBadge())
.setTicker(options.getMessage())
.setSmallIcon(options.getSmallIcon())
.setLargeIcon(options.getIcon())
.setAutoCancel(options.getAutoCancel())
.setOngoing(options.getOngoing())
.setLights(options.getColor(), 500, 500)
.setDeleteIntent(dpi);
if (sound != null) {
notification.setSound(sound);
}
if (Build.VERSION.SDK_INT > 16) {
notification.setStyle(new NotificationCompat.BigTextStyle()
.bigText(options.getMessage()));
}
setClickEvent(notification);
return notification;
}
/**
* Adds an onclick handler to the notification
*/
private Builder setClickEvent (Builder notification) {
Intent intent = new Intent(context, receiverActivity)
.putExtra(OPTIONS, options.getJSONObject().toString())
.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
int requestCode = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return notification.setContentIntent(contentIntent);
}
}
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
/**
* Class that helps to store the options that can be specified per alarm.
*/
public class Options {
private JSONObject options = new JSONObject();
private String packageName = null;
private long interval = 0;
private Context context;
public Options(Context context){
this.context= context;
this.packageName = context.getPackageName();
}
/**
* Parses the given properties
*/
public Options parse (JSONObject options) {
String repeat = options.optString("repeat");
this.options = options;
if (repeat.equalsIgnoreCase("secondly")) {
interval = 1000;
} if (repeat.equalsIgnoreCase("minutely")) {
interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES / 15;
} if (repeat.equalsIgnoreCase("hourly")) {
interval = AlarmManager.INTERVAL_HOUR;
} if (repeat.equalsIgnoreCase("daily")) {
interval = AlarmManager.INTERVAL_DAY;
} else if (repeat.equalsIgnoreCase("weekly")) {
interval = AlarmManager.INTERVAL_DAY*7;
} else if (repeat.equalsIgnoreCase("monthly")) {
interval = AlarmManager.INTERVAL_DAY*31; // 31 days
} else if (repeat.equalsIgnoreCase("yearly")) {
interval = AlarmManager.INTERVAL_DAY*365;
} else {
try {
interval = Integer.parseInt(repeat) * 60000;
} catch (Exception e) {};
}
return this;
}
/**
* Set new time according to interval
*/
public Options moveDate () {
try {
options.put("date", (getDate() + interval) / 1000);
} catch (JSONException e) {}
return this;
}
/**
* Returns options as JSON object
*/
public JSONObject getJSONObject() {
return options;
}
/**
* Returns time in milliseconds when notification is scheduled to fire
*/
public long getDate() {
return options.optLong("date", 0) * 1000;
}
/**
* Returns time in milliseconds when the notification was scheduled first
*/
public long getInitialDate() {
return options.optLong("initialDate", 0);
}
/**
* Returns time as calender
*/
public Calendar getCalendar () {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(getDate()));
return calendar;
}
/**
* Returns the notification's message
*/
public String getMessage () {
return options.optString("message", "");
}
/**
* Returns the notification's title
*/
public String getTitle () {
return options.optString("title", "");
}
/**
* Returns the path of the notification's sound file
*/
public Uri getSound () {
Uri soundUri = null;
try{
soundUri = Uri.parse(options.optString("soundUri"));
return soundUri;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* Returns the icon's ID
*/
public Bitmap getIcon () {
String icon = options.optString("icon", "icon");
Bitmap bmp = null;
Uri iconUri = null;
try{
iconUri = Uri.parse(options.optString("iconUri"));
} catch (Exception e){
e.printStackTrace();
}
if (iconUri != null) {
bmp = getIconFromUri(iconUri);
}
if (bmp == null) {
bmp = getIconFromRes(icon);
}
return bmp;
}
/**
* Returns the small icon's ID
*/
public int getSmallIcon () {
int resId = 0;
String iconName = options.optString("smallIcon", "");
resId = getIconValue(packageName, iconName);
if (resId == 0) {
resId = getIconValue("android", iconName);
}
if (resId == 0) {
resId = getIconValue(packageName, "icon");
}
return options.optInt("smallIcon", resId);
}
/**
* Returns notification repetition interval (daily, weekly, monthly, yearly)
*/
public long getInterval () {
return interval;
}
/**
* Returns notification badge number
*/
public int getBadge () {
return options.optInt("badge", 0);
}
/**
* Returns PluginResults' callback ID
*/
public String getId () {
return options.optString("id", "0");
}
/**
* Returns whether notification is cancelled automatically when clicked.
*/
public Boolean getAutoCancel () {
return options.optBoolean("autoCancel", false);
}
/**
* Returns whether the notification is ongoing (uncancellable). Android only.
*/
public Boolean getOngoing () {
return options.optBoolean("ongoing", false);
}
/**
* Returns additional data as string
*/
public String getJSON () {
return options.optString("json", "");
}
/**
* @return
* The notification color for LED
*/
public int getColor () {
String hexColor = options.optString("led", "000000");
int aRGB = Integer.parseInt(hexColor,16);
aRGB += 0xFF000000;
return aRGB;
}
/**
* Shows the behavior of notifications when the application is in foreground
*
*/
public boolean getForegroundMode(){
return options.optBoolean("foregroundMode",false);
}
/**
* Returns numerical icon Value
*
* @param {String} className
* @param {String} iconName
*/
private int getIconValue (String className, String iconName) {
int icon = 0;
try {
Class<?> klass = Class.forName(className + ".R$drawable");
icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class);
} catch (Exception e) {}
return icon;
}
/**
* Converts an resource to Bitmap.
*
* @param icon
* The resource name
* @return
* The corresponding bitmap
*/
private Bitmap getIconFromRes (String icon) {
Resources res = context.getResources();
int iconId = 0;
iconId = getIconValue(packageName, icon);
if (iconId == 0) {
iconId = getIconValue("android", icon);
}
if (iconId == 0) {
iconId = android.R.drawable.ic_menu_info_details;
}
Bitmap bmp = BitmapFactory.decodeResource(res, iconId);
return bmp;
}
/**
* Converts an Image URI to Bitmap.
*
* @param src
* The internal image URI
* @return
* The corresponding bitmap
*/
private Bitmap getIconFromUri (Uri uri) {
Bitmap bmp = null;
try {
InputStream input = context.getContentResolver().openInputStream(uri);
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
/**
* Function to set the value of "initialDate" in the JSONArray
* @param args The given JSONArray
* @return A new JSONArray with the parameter "initialDate" set.
*/
public void setInitDate(){
long initialDate = options.optLong("date", 0) * 1000;
try {
options.put("initialDate", initialDate);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
......@@ -26,6 +26,12 @@
// Execute all queued events
- (void) deviceready:(CDVInvokedUrlCommand*)command;
// Inform if the app has the permission to show notifications
- (void) hasPermission:(CDVInvokedUrlCommand*)command;
// Register permission to show notifications
- (void) registerPermission:(CDVInvokedUrlCommand*)command;
// Schedule a new notification
- (void) add:(CDVInvokedUrlCommand*)command;
// Update a notification
......@@ -34,21 +40,26 @@
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all currently scheduled notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// Check if a notification with an ID is scheduled
// If a notification with an ID exists
- (void) exist:(CDVInvokedUrlCommand*)command;
// If a notification with an ID was scheduled
- (void) isScheduled:(CDVInvokedUrlCommand*)command;
// Check if a notification with an ID was triggered
// If a notification with an ID was triggered
- (void) isTriggered:(CDVInvokedUrlCommand*)command;
// List all ids from all local notifications
- (void) getAllIds:(CDVInvokedUrlCommand*)command;
// List all ids from all pending notifications
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command;
// List all ids from all triggered notifications
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command;
// List all properties for given scheduled notifications
// Property list for given local notifications
- (void) getAll:(CDVInvokedUrlCommand*)command;
// Property list for given scheduled notifications
- (void) getScheduled:(CDVInvokedUrlCommand*)command;
// List all properties for given triggered notifications
// Property list for given triggered notifications
- (void) getTriggered:(CDVInvokedUrlCommand*)command;
// Inform if the app has the permission to show notifications
- (void) hasPermission:(CDVInvokedUrlCommand*)command;
// Register permission to show notifications
- (void) registerPermission:(CDVInvokedUrlCommand*)command;
@end
......@@ -162,6 +162,34 @@
}
/**
* If a notification by ID exists.
*
* @param id
* The ID of the notification
*/
- (void) exist:(CDVInvokedUrlCommand *)command
{
[self.commandDelegate runInBackground:^{
NSString* id = [[command arguments]
objectAtIndex:0];
CDVPluginResult* result;
UILocalNotification* notification;
notification = [[UIApplication sharedApplication]
localNotificationWithId:id];
bool exists = notification != NULL;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:exists];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* If a notification by ID is scheduled.
*
* @param id
......@@ -218,6 +246,26 @@
}
/**
* List all ids from all local notifications.
*/
- (void) getAllIds:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
CDVPluginResult* result;
NSArray* notIds;
notIds = [[UIApplication sharedApplication]
localNotificationIds];
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:notIds];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* List all ids from all pending notifications.
*/
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command
......@@ -258,7 +306,36 @@
}
/**
* List all properties for given scheduled notifications.
* Property list for given local notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) getAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
CDVPluginResult* result;
if (ids.count == 0) {
notifications = [[UIApplication sharedApplication]
localNotificationOptions];
} else {
notifications = [[UIApplication sharedApplication]
localNotificationOptions:ids];
}
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:notifications];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Property list for given scheduled notifications.
*
* @param ids
* The IDs of the notifications
......@@ -287,7 +364,7 @@
}
/**
* List all properties for given triggered notifications.
* Property list for given triggered notifications.
*
* @param ids
* The IDs of the notifications
......
......@@ -21,7 +21,11 @@
@interface UIApplication (APPLocalNotification)
@property (readonly, getter=localNotifications) NSArray* localNotifications;
@property (readonly, getter=scheduledLocalNotifications2) NSArray* triggeredLocalNotifications2;
@property (readonly, getter=triggeredLocalNotifications) NSArray* triggeredLocalNotifications;
@property (readonly, getter=localNotificationIds) NSArray* localNotificationIds;
@property (readonly, getter=triggeredLocalNotificationIds) NSArray* triggeredLocalNotificationIds;
@property (readonly, getter=scheduledLocalNotificationIds) NSArray* scheduledLocalNotificationIds;
......@@ -29,17 +33,26 @@
- (BOOL) hasPermissionToScheduleLocalNotifications;
// Ask for permission to schedule local notifications
- (void) registerPermissionToScheduleLocalNotifications;
// Get the scheduled local notification by ID
// Get local notification by ID
- (UILocalNotification*) localNotificationWithId:(NSString*)id;
// Get scheduled local notification by ID
- (UILocalNotification*) scheduledLocalNotificationWithId:(NSString*)id;
// Get the triggered local notification by ID
// Get triggered local notification by ID
- (UILocalNotification*) triggeredLocalNotificationWithId:(NSString*)id;
// List of properties from all scheduled notifications
// Property list from all local notifications
- (NSArray*) localNotificationOptions;
// Property list from all scheduled notifications
- (NSArray*) scheduledLocalNotificationOptions;
// List of properties from given scheduled notifications
- (NSArray*) scheduledLocalNotificationOptions:(NSArray*)ids;
// List of properties from all triggered notifications
// Property list from all triggered notifications
- (NSArray*) triggeredLocalNotificationOptions;
// List of properties from given triggered notifications
// Property list from given local notifications
- (NSArray*) localNotificationOptions:(NSArray*)ids;
// Property list from given scheduled notifications
- (NSArray*) scheduledLocalNotificationOptions:(NSArray*)ids;
// Property list from given triggered notifications
- (NSArray*) triggeredLocalNotificationOptions:(NSArray*)ids;
@end
......@@ -72,18 +72,55 @@
#pragma mark LocalNotifications
/**
* List of all local notifications which have been added
* but not yet removed from the notification center.
*/
- (NSArray*) localNotifications
{
NSArray* scheduledNotifications = self.scheduledLocalNotifications;
NSMutableArray* notifications = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in scheduledNotifications)
{
if (notification) {
[notifications addObject:notification];
}
}
return notifications;
}
/**
* List of all local notifications which have been scheduled
* and not yet removed from the notification center.
*/
- (NSArray*) scheduledLocalNotifications2
{
NSArray* scheduledNotifications = self.scheduledLocalNotifications;
NSMutableArray* notifications = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in scheduledNotifications)
{
if (notification && [notification wasScheduled]) {
[notifications addObject:notification];
}
}
return notifications;
}
/**
* List of all triggered local notifications which have been scheduled
* and not yet removed the notification center.
*/
- (NSArray*) triggeredLocalNotifications
{
NSArray* scheduledNotifications = self.scheduledLocalNotifications;
NSArray* notifications = self.localNotifications;
NSMutableArray* triggeredNotifications = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in scheduledNotifications)
for (UILocalNotification* notification in notifications)
{
if (notification && [notification wasTriggered])
{
if ([notification wasTriggered]) {
[triggeredNotifications addObject:notification];
}
}
......@@ -93,18 +130,35 @@
/**
* List of all triggered local notifications IDs which have been scheduled
* and not yet removed the notification center.
* and not yet removed from the notification center.
*/
- (NSArray*) localNotificationIds
{
NSArray* notifications = self.localNotifications;
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[ids addObject:notification.options.id];
}
return ids;
}
/**
* List of all added local notifications IDs which have been scheduled
* and not yet removed from the notification center.
*/
- (NSArray*) triggeredLocalNotificationIds
{
NSArray* notifications = self.triggeredLocalNotifications;
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[ids addObject:notification.options.id];
}
return ids;
}
......@@ -113,32 +167,50 @@
*/
- (NSArray*) scheduledLocalNotificationIds
{
NSArray* notifications = self.scheduledLocalNotifications;
NSArray* notifications = self.scheduledLocalNotifications2;
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
if (notification) {
[ids addObject:notification.options.id];
}
[ids addObject:notification.options.id];
}
return ids;
}
/**
* Get the scheduled local notification by ID.
* Get local notification by ID.
*
* @param id
* Notification ID
*/
- (UILocalNotification*) localNotificationWithId:(NSString*)id
{
NSArray* notifications = self.localNotifications;
for (UILocalNotification* notification in notifications)
{
if ([notification.options.id isEqualToString:id]) {
return notification;
}
}
return NULL;
}
/**
* Get scheduled local notification by ID.
*
* @param id
* Notification ID
*/
- (UILocalNotification*) scheduledLocalNotificationWithId:(NSString*)id
{
NSArray* notifications = self.scheduledLocalNotifications;
NSArray* notifications = self.scheduledLocalNotifications2;
for (UILocalNotification* notification in notifications)
{
if (notification && [notification.options.id isEqualToString:id]) {
if ([notification.options.id isEqualToString:id]) {
return notification;
}
}
......@@ -147,14 +219,14 @@
}
/**
* Get the triggered local notification by ID.
* Get triggered local notification by ID.
*
* @param id
* Notification ID
*/
- (UILocalNotification*) triggeredLocalNotificationWithId:(NSString*)id
{
UILocalNotification* notification = [self scheduledLocalNotificationWithId:id];
UILocalNotification* notification = [self localNotificationWithId:id];
if (notification && [notification wasTriggered]) {
return notification;
......@@ -164,57 +236,94 @@
}
/**
* List of properties from all notifications.
*/
- (NSArray*) localNotificationOptions
{
NSArray* notifications = self.localNotifications;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[options addObject:notification.userInfo];
}
return options;
}
/**
* List of properties from all scheduled notifications.
*/
- (NSArray*) scheduledLocalNotificationOptions
{
NSArray* notifications = self.scheduledLocalNotifications;
NSArray* notifications = [self scheduledLocalNotifications2];
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
if (notification) {
[options addObject:notification.userInfo];
}
[options addObject:notification.userInfo];
}
return options;
}
/**
* List of properties from given scheduled notifications.
* List of properties from all triggered notifications.
*/
- (NSArray*) triggeredLocalNotificationOptions
{
NSArray* notifications = self.triggeredLocalNotifications;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[options addObject:notification.userInfo];
}
return options;
}
/**
* List of properties from given local notifications.
*
* @param ids
* Notification IDs
*/
- (NSArray*) scheduledLocalNotificationOptions:(NSArray*)ids
- (NSArray*) localNotificationOptions:(NSArray*)ids
{
UILocalNotification* notification;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (NSString* id in ids)
{
notification = [self scheduledLocalNotificationWithId:id];
notification = [self localNotificationWithId:id];
if (notification) {
[options addObject:notification.userInfo];
}
}
return options;
}
/**
* List of properties from all triggered notifications.
* List of properties from given scheduled notifications.
*
* @param ids
* Notification IDs
*/
- (NSArray*) triggeredLocalNotificationOptions
- (NSArray*) scheduledLocalNotificationOptions:(NSArray*)ids
{
NSArray* notifications = self.triggeredLocalNotifications;
UILocalNotification* notification;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
for (NSString* id in ids)
{
[options addObject:notification.userInfo];
notification = [self scheduledLocalNotificationWithId:id];
if (notification) {
[options addObject:notification.userInfo];
}
}
return options;
......
......@@ -31,6 +31,8 @@
- (double) timeIntervalSinceFireDate;
// If the fire date was in the past
- (BOOL) wasInThePast;
// If the notification was already scheduled
- (BOOL) wasScheduled;
// If the notification was already triggered
- (BOOL) wasTriggered;
// If the notification was updated
......
......@@ -143,6 +143,32 @@ static char optionsKey;
}
/**
* Encode the user info dict to JSON.
*/
- (NSString*) encodeToJSON
{
NSString* json;
NSData* data;
NSMutableDictionary* obj = [self.userInfo mutableCopy];
[obj removeObjectForKey:@"json"];
[obj removeObjectForKey:@"updatedAt"];
data = [NSJSONSerialization dataWithJSONObject:obj
options:NSJSONWritingPrettyPrinted
error:Nil];
json = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
return [json stringByReplacingOccurrencesOfString:@"\n"
withString:@""];
}
#pragma mark -
#pragma mark State
/**
* If the fire date was in the past.
*/
- (BOOL) wasInThePast
......@@ -150,6 +176,12 @@ static char optionsKey;
return [self timeIntervalSinceFireDate] > 0;
}
// If the notification was already scheduled
- (BOOL) wasScheduled
{
return [self isRepeating] || ![self wasInThePast];
}
/**
* If the notification was already triggered.
*/
......@@ -158,9 +190,9 @@ static char optionsKey;
NSDate* now = [NSDate date];
NSDate* fireDate = self.fireDate;
bool isLaterThanOrEqualTo = !([now compare:fireDate] == NSOrderedAscending);
bool isLaterThanFireDate = !([now compare:fireDate] == NSOrderedAscending);
return isLaterThanOrEqualTo;
return isLaterThanFireDate;
}
/**
......@@ -187,27 +219,4 @@ static char optionsKey;
return [self.options isRepeating];
}
/**
* Encode the user info dict to JSON.
*/
- (NSString*) encodeToJSON
{
NSString* json;
NSData* data;
NSMutableDictionary* obj = [self.userInfo mutableCopy];
[obj removeObjectForKey:@"json"];
[obj removeObjectForKey:@"updatedAt"];
data = [NSJSONSerialization dataWithJSONObject:obj
options:NSJSONWritingPrettyPrinted
error:Nil];
json = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
return [json stringByReplacingOccurrencesOfString:@"\n"
withString:@""];
}
@end
......@@ -67,7 +67,8 @@ exports._defaults = {
badge: -1,
id: '0',
json: '',
repeat: ''
repeat: '',
date: undefined
};
......@@ -208,6 +209,29 @@ exports.cancelAll = function (callback, scope) {
};
/**
* Check if a notification with an ID exists.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/
exports.exist = function (id, callback, scope) {
var notId = (id || '0').toString();
this.exec('exist', notId, callback, scope);
};
/**
* Alias for `exist`.
*/
exports.exists = function () {
this.exist.apply(this, arguments);
};
/**
* Check if a notification with an ID is scheduled.
*
* @param {String} id
......@@ -240,7 +264,26 @@ exports.isTriggered = function (id, callback, scope) {
};
/**
* List all currently pending notifications.
* List all local notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/
exports.getAllIds = function (callback, scope) {
this.exec('getAllIds', null, callback, scope);
};
/**
* Alias for `getAllIds`.
*/
exports.getIds = function () {
this.getAllIds.apply(this, arguments);
};
/**
* List all scheduled notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
......@@ -252,7 +295,7 @@ exports.getScheduledIds = function (callback, scope) {
};
/**
* List all triggered notifications.
* List all triggered notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
......@@ -264,7 +307,50 @@ exports.getTriggeredIds = function (callback, scope) {
};
/**
* List all properties for given scheduled notifications.
* Property list for given local notifications.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/
exports.get = function () {
var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
var ids = args[0],
callback = args[1],
scope = args[2];
if (!Array.isArray(ids)) {
ids = [ids];
}
ids = this.convertIds(ids);
this.exec('getAll', ids, callback, scope);
};
/**
* Property list for all local notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/
exports.getAll = function (callback, scope) {
this.exec('getAll', null, callback, scope);
};
/**
* Property list for given scheduled notifications.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
......@@ -307,7 +393,7 @@ exports.getAllScheduled = function (callback, scope) {
};
/**
* List all properties for given triggered notifications.
* Property list for given triggered notifications.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
......
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.StrictMode;
import android.util.Log;
public class Asset {
private Activity activity;
protected final String STORAGE_FOLDER;
/**
* Constructor of Asset Class. Takes Applications Activity and a foldername for temporary saving.
*
*@param activity Applications Activity
*@param storageFolder foldername for temporary saving.
*/
public Asset(Activity activity,String storageFolder){
this.activity = activity;
this.STORAGE_FOLDER = storageFolder;
}
/**
* Parse given PathStrings to Uris
* @param notification Notifications JSONObject
* @return new Notification JSONObject with additional iconUri and soundUri
*/
public JSONObject parseURIs(JSONObject notification){
//sound
String sound = notification.optString("sound", null);
Uri soundUri = null;
if (sound != null) {
try {
int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class);
soundUri = RingtoneManager.getDefaultUri(soundId);
} catch (Exception e) {
soundUri = getURIfromPath(sound);
}
}
if (soundUri!= null&&soundUri!=Uri.EMPTY){
try{
notification.put("soundUri", soundUri.toString());
} catch (JSONException jse){
jse.printStackTrace();
}
}
//image
String icon = notification.optString("icon", "icon");
Uri iconUri = null;
iconUri = getURIfromPath(icon);
if (iconUri != Uri.EMPTY&&iconUri != null){
try{
notification.put("iconUri", iconUri.toString());
} catch (JSONException jse){
jse.printStackTrace();
}
}
return notification;
}
/**
* The URI for a path.
*
* @param path The given path
*
* @return The URI pointing to the given path
*/
public Uri getURIfromPath(String path){
if (path.startsWith("res:")) {
return getUriForResourcePath(path);
} else if (path.startsWith("file:///")) {
return getUriForAbsolutePath(path);
} else if (path.startsWith("file://")) {
return getUriForAssetPath(path);
} else if (path.startsWith("http")){
return getUriForHTTP(path);
}
return Uri.parse(path);
}
/**
* The URI for a file.
*
* @param path
* The given absolute path
*
* @return The URI pointing to the given path
*/
private Uri getUriForAbsolutePath(String path) {
String absPath = path.replaceFirst("file://", "");
File file = new File(absPath);
if (!file.exists()) {
Log.e("Asset", "File not found: " + file.getAbsolutePath());
return Uri.EMPTY;
}
return Uri.fromFile(file);
}
/**
* The URI for an asset.
*
* @param path
* The given asset path
*
* @return The URI pointing to the given path
*/
private Uri getUriForAssetPath(String path) {
String resPath = path.replaceFirst("file:/", "www");
String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
File file = new File(storage, fileName);
new File(storage).mkdir();
try {
AssetManager assets = activity.getAssets();
FileOutputStream outStream = new FileOutputStream(file);
InputStream inputStream = assets.open(resPath);
copyFile(inputStream, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (Exception e) {
Log.e("Asset", "File not found: assets/" + resPath);
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
* The URI for a resource.
*
* @param path
* The given relative path
*
* @return The URI pointing to the given path
*/
private Uri getUriForResourcePath(String path) {
String resPath = path.replaceFirst("res://", "");
String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = resPath.substring(resPath.lastIndexOf('.'));
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
int resId = getResId(resPath);
File file = new File(storage, resName + extension);
if (resId == 0) {
Log.e("Asset", "File not found: " + resPath);
return Uri.EMPTY;
}
new File(storage).mkdir();
try {
Resources res = activity.getResources();
FileOutputStream outStream = new FileOutputStream(file);
InputStream inputStream = res.openRawResource(resId);
copyFile(inputStream, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (Exception e) {
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
*Get Uri for HTTP Content
* @param path HTTP adress
* @return Uri of the downloaded file
*/
private Uri getUriForHTTP(String path) {
try {
URL url = new URL(path);
String fileName = path.substring(path.lastIndexOf('/') + 1);
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = path.substring(path.lastIndexOf('.'));
File dir = activity.getExternalCacheDir();
if (dir == null) {
Log.e("Asset", "Missing external cache dir");
return Uri.EMPTY;
}
String storage = dir.toString() + STORAGE_FOLDER;
File file = new File(storage, resName + extension);
new File(storage).mkdir();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
FileOutputStream outStream = new FileOutputStream(file);
copyFile(input, outStream);
outStream.flush();
outStream.close();
return Uri.fromFile(file);
} catch (MalformedURLException e) {
Log.e("Asset", "Incorrect URL");
e.printStackTrace();
} catch (FileNotFoundException e) {
Log.e("Asset", "Failed to create new File from HTTP Content");
e.printStackTrace();
} catch (IOException e) {
Log.e("Asset", "No Input can be created from http Stream");
e.printStackTrace();
}
return Uri.EMPTY;
}
/**
* Writes an InputStream to an OutputStream
*
* @param in
* The input stream
* @param out
* The output stream
*/
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
/**
* @return The resource ID for the given resource.
*/
private int getResId(String resPath) {
Resources res = activity.getResources();
int resId;
String pkgName = getPackageName();
String dirName = "drawable";
String fileName = resPath;
if (resPath.contains("/")) {
dirName = resPath.substring(0, resPath.lastIndexOf('/'));
fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
}
String resName = fileName.substring(0, fileName.lastIndexOf('.'));
resId = res.getIdentifier(resName, dirName, pkgName);
if (resId == 0) {
resId = res.getIdentifier(resName, "drawable", pkgName);
}
return resId;
}
/**
* The name for the package.
*
* @return The package name
*/
private String getPackageName() {
return activity.getPackageName();
}
}
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
public class NotificationBuilder {
private Options options;
private Context context;
private Builder notification;
private final String OPTIONS;
private Class<?> deleteIntentReceiver;
private Class<?> receiverActivity;
/**
* Constructor of NotificationBuilder
* @param options
* @param context
* @param OPTIONS
* @param deleteIntentReceiver
* @param receiverActivity
*/
public NotificationBuilder(Options options,Context context, String OPTIONS,
Class<?> deleteIntentReceiver, Class<?> receiverActivity){
this.options = options;
this.context = context;
this.OPTIONS = OPTIONS;
this.deleteIntentReceiver = deleteIntentReceiver;
this.receiverActivity = receiverActivity;
}
/**
* Creates the notification.
*/
@SuppressLint("NewApi")
public Builder buildNotification () {
Uri sound = options.getSound();
//DeleteIntent is called when the user clears a notification manually
Intent deleteIntent = new Intent(context, deleteIntentReceiver)
.setAction("" + options.getId())
.putExtra(OPTIONS, options.getJSONObject().toString());
PendingIntent dpi = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification = new NotificationCompat.Builder(context)
.setDefaults(0) // Do not inherit any defaults
.setContentTitle(options.getTitle())
.setContentText(options.getMessage())
.setNumber(options.getBadge())
.setTicker(options.getMessage())
.setSmallIcon(options.getSmallIcon())
.setLargeIcon(options.getIcon())
.setAutoCancel(options.getAutoCancel())
.setOngoing(options.getOngoing())
.setLights(options.getColor(), 500, 500)
.setDeleteIntent(dpi);
if (sound != null) {
notification.setSound(sound);
}
if (Build.VERSION.SDK_INT > 16) {
notification.setStyle(new NotificationCompat.BigTextStyle()
.bigText(options.getMessage()));
}
setClickEvent(notification);
return notification;
}
/**
* Adds an onclick handler to the notification
*/
private Builder setClickEvent (Builder notification) {
Intent intent = new Intent(context, receiverActivity)
.putExtra(OPTIONS, options.getJSONObject().toString())
.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
int requestCode = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return notification.setContentIntent(contentIntent);
}
}
/*
Copyright 2013-2014 appPlant UG
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package de.appplant.cordova.plugin.notification;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
/**
* Class that helps to store the options that can be specified per alarm.
*/
public class Options {
private JSONObject options = new JSONObject();
private String packageName = null;
private long interval = 0;
private Context context;
public Options(Context context){
this.context= context;
this.packageName = context.getPackageName();
}
/**
* Parses the given properties
*/
public Options parse (JSONObject options) {
String repeat = options.optString("repeat");
this.options = options;
if (repeat.equalsIgnoreCase("secondly")) {
interval = 1000;
} if (repeat.equalsIgnoreCase("minutely")) {
interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES / 15;
} if (repeat.equalsIgnoreCase("hourly")) {
interval = AlarmManager.INTERVAL_HOUR;
} if (repeat.equalsIgnoreCase("daily")) {
interval = AlarmManager.INTERVAL_DAY;
} else if (repeat.equalsIgnoreCase("weekly")) {
interval = AlarmManager.INTERVAL_DAY*7;
} else if (repeat.equalsIgnoreCase("monthly")) {
interval = AlarmManager.INTERVAL_DAY*31; // 31 days
} else if (repeat.equalsIgnoreCase("yearly")) {
interval = AlarmManager.INTERVAL_DAY*365;
} else {
try {
interval = Integer.parseInt(repeat) * 60000;
} catch (Exception e) {};
}
return this;
}
/**
* Set new time according to interval
*/
public Options moveDate () {
try {
options.put("date", (getDate() + interval) / 1000);
} catch (JSONException e) {}
return this;
}
/**
* Returns options as JSON object
*/
public JSONObject getJSONObject() {
return options;
}
/**
* Returns time in milliseconds when notification is scheduled to fire
*/
public long getDate() {
return options.optLong("date", 0) * 1000;
}
/**
* Returns time in milliseconds when the notification was scheduled first
*/
public long getInitialDate() {
return options.optLong("initialDate", 0);
}
/**
* Returns time as calender
*/
public Calendar getCalendar () {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(getDate()));
return calendar;
}
/**
* Returns the notification's message
*/
public String getMessage () {
return options.optString("message", "");
}
/**
* Returns the notification's title
*/
public String getTitle () {
return options.optString("title", "");
}
/**
* Returns the path of the notification's sound file
*/
public Uri getSound () {
Uri soundUri = null;
try{
soundUri = Uri.parse(options.optString("soundUri"));
return soundUri;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* Returns the icon's ID
*/
public Bitmap getIcon () {
String icon = options.optString("icon", "icon");
Bitmap bmp = null;
Uri iconUri = null;
try{
iconUri = Uri.parse(options.optString("iconUri"));
} catch (Exception e){
e.printStackTrace();
}
if (iconUri != null) {
bmp = getIconFromUri(iconUri);
}
if (bmp == null) {
bmp = getIconFromRes(icon);
}
return bmp;
}
/**
* Returns the small icon's ID
*/
public int getSmallIcon () {
int resId = 0;
String iconName = options.optString("smallIcon", "");
resId = getIconValue(packageName, iconName);
if (resId == 0) {
resId = getIconValue("android", iconName);
}
if (resId == 0) {
resId = getIconValue(packageName, "icon");
}
return options.optInt("smallIcon", resId);
}
/**
* Returns notification repetition interval (daily, weekly, monthly, yearly)
*/
public long getInterval () {
return interval;
}
/**
* Returns notification badge number
*/
public int getBadge () {
return options.optInt("badge", 0);
}
/**
* Returns PluginResults' callback ID
*/
public String getId () {
return options.optString("id", "0");
}
/**
* Returns whether notification is cancelled automatically when clicked.
*/
public Boolean getAutoCancel () {
return options.optBoolean("autoCancel", false);
}
/**
* Returns whether the notification is ongoing (uncancellable). Android only.
*/
public Boolean getOngoing () {
return options.optBoolean("ongoing", false);
}
/**
* Returns additional data as string
*/
public String getJSON () {
return options.optString("json", "");
}
/**
* @return
* The notification color for LED
*/
public int getColor () {
String hexColor = options.optString("led", "000000");
int aRGB = Integer.parseInt(hexColor,16);
aRGB += 0xFF000000;
return aRGB;
}
/**
* Shows the behavior of notifications when the application is in foreground
*
*/
public boolean getForegroundMode(){
return options.optBoolean("foregroundMode",false);
}
/**
* Returns numerical icon Value
*
* @param {String} className
* @param {String} iconName
*/
private int getIconValue (String className, String iconName) {
int icon = 0;
try {
Class<?> klass = Class.forName(className + ".R$drawable");
icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class);
} catch (Exception e) {}
return icon;
}
/**
* Converts an resource to Bitmap.
*
* @param icon
* The resource name
* @return
* The corresponding bitmap
*/
private Bitmap getIconFromRes (String icon) {
Resources res = context.getResources();
int iconId = 0;
iconId = getIconValue(packageName, icon);
if (iconId == 0) {
iconId = getIconValue("android", icon);
}
if (iconId == 0) {
iconId = android.R.drawable.ic_menu_info_details;
}
Bitmap bmp = BitmapFactory.decodeResource(res, iconId);
return bmp;
}
/**
* Converts an Image URI to Bitmap.
*
* @param src
* The internal image URI
* @return
* The corresponding bitmap
*/
private Bitmap getIconFromUri (Uri uri) {
Bitmap bmp = null;
try {
InputStream input = context.getContentResolver().openInputStream(uri);
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
/**
* Function to set the value of "initialDate" in the JSONArray
* @param args The given JSONArray
* @return A new JSONArray with the parameter "initialDate" set.
*/
public void setInitDate(){
long initialDate = options.optLong("date", 0) * 1000;
try {
options.put("initialDate", initialDate);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment