android phonegap notifications(Notification Bar) from a background task

Posted: February 5, 2013 in mobile

now i need to remind my user about workouts. It can choose how much time before to alert about a workout. I want the alert to apear in the Notification Bar and the checking of the workout times should be done in the background without my “main” activity in the front.

So the first link i c is this

Local Notification Android plugin

looks real good, i hope it will take little time to understand how to use it.

also found this more updated link with changes inside.

but i found that i needed to do even more changes in LocalNotification.JAVA because of the Plugin–>CordovaPlugin

this pretty easy but I still put it here

package com.phonegap.plugin.localnotification;

import java.util.Calendar;

import org.json.JSONArray;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;

/**
* This plugin utilizes the Android AlarmManager in combination with StatusBar
* notifications. When a local notification is scheduled the alarm manager takes
* care of firing the event. When the event is processed, a notification is put
* in the Android status bar.
*
* @author Daniel van ‘t Oever
*/
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 optionsArr, CallbackContext callbackContext) {
alarm = new AlarmHelper(cordova.getContext());
Log.d(PLUGIN_NAME, “Plugin execute called with action: ” + action);

PluginResult result = null;

final AlarmOptions alarmOptions = new AlarmOptions();
alarmOptions.parseOptions(optionsArr);

/*
* Determine which action of the plugin needs to be invoked
*/
String alarmId = alarmOptions.getNotificationId();
if (action.equalsIgnoreCase(“add”)) {
final boolean daily = alarmOptions.isRepeatDaily();
final String title = alarmOptions.getAlarmTitle();
final String subTitle = alarmOptions.getAlarmSubTitle();
final String ticker = alarmOptions.getAlarmTicker();

persistAlarm(alarmId, optionsArr);
this.add(daily, title, subTitle, ticker, alarmId, alarmOptions.getCal());
return true;
} else if (action.equalsIgnoreCase(“cancel”)) {
unpersistAlarm(alarmId);
this.cancelNotification(alarmId);
return true;
} else if (action.equalsIgnoreCase(“cancelall”)) {
unpersistAlarmAll();
this.cancelAllNotifications();
return true;
}

return true;
}

/**
* Set an alarm
*
* @param repeatDaily
* If true, the alarm interval will be set to one day.
* @param alarmTitle
* The title of the alarm as shown in the Android notification
* panel
* @param alarmSubTitle
* The subtitle of the alarm
* @param alarmId
* The unique ID of the notification
* @param cal
* A calendar object that represents the time at which the alarm
* should first be started
* @return A pluginresult.
*/
public PluginResult add(boolean repeatDaily, String alarmTitle, String alarmSubTitle, String alarmTicker,
String alarmId, Calendar cal) {
final long triggerTime = cal.getTimeInMillis();
final String recurring = repeatDaily ? “daily” : “onetime”;

Log.d(PLUGIN_NAME, “Adding ” + recurring + ” notification: ‘” + alarmTitle + alarmSubTitle + “‘ with id: ”
+ alarmId + ” at timestamp: ” + triggerTime);

boolean result = alarm.addAlarm(repeatDaily, alarmTitle, alarmSubTitle, alarmTicker, alarmId, cal);
if (result) {
return new PluginResult(PluginResult.Status.OK);
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
}

/**
* Cancel a specific notification that was previously registered.
*
* @param notificationId
* The original ID of the notification that was used when it was
* registered using addNotification()
*/
public PluginResult cancelNotification(String notificationId) {
Log.d(PLUGIN_NAME, “cancelNotification: Canceling event with id: ” + notificationId);

boolean result = alarm.cancelAlarm(notificationId);
if (result) {
return new PluginResult(PluginResult.Status.OK);
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
}

/**
* Cancel all notifications that were created by this plugin.
*/
public PluginResult cancelAllNotifications() {
Log.d(PLUGIN_NAME, “cancelAllNotifications: cancelling all events for this application”);
/*
* 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.
*/
final SharedPreferences alarmSettings = cordova.getContext().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE);
final boolean result = alarm.cancelAll(alarmSettings);

if (result) {
return new PluginResult(PluginResult.Status.OK);
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
}

/**
* Persist the information of this alarm to the Android Shared Preferences.
* This will allow the application to restore the alarm upon device reboot.
* Also this is used by the cancelAllNotifications method.
*
* @see #cancelAllNotifications()
*
* @param optionsArr
* The assumption is that parseOptions has been called already.
*
* @return true when successfull, otherwise false
*/
private boolean persistAlarm(String alarmId, JSONArray optionsArr) {
final Editor alarmSettingsEditor = cordova.getContext().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE).edit();

alarmSettingsEditor.putString(alarmId, optionsArr.toString());

return alarmSettingsEditor.commit();
}

/**
* Remove a specific alarm from the Android shared Preferences
*
* @param alarmId
* The Id of the notification that must be removed.
*
* @return true when successfull, otherwise false
*/
private boolean unpersistAlarm(String alarmId) {
final Editor alarmSettingsEditor = cordova.getContext().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE).edit();

alarmSettingsEditor.remove(alarmId);

return alarmSettingsEditor.commit();
}

/**
* Clear all alarms from the Android shared Preferences
*
* @return true when successfull, otherwise false
*/
private boolean unpersistAlarmAll() {
final Editor alarmSettingsEditor = cordova.getContext().getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE).edit();

alarmSettingsEditor.clear();

return alarmSettingsEditor.commit();
}
}

 

now i tried to change things and found new issues, read this in my next post

Advertisements
Comments
  1. […] はい、やってみました。 見事に……動きません(; ・`д・´) なんでだろぉ、と原因がわからなかったので、海外のフォーラムを徘徊してみました。 するとこんな記事が↓ https://codefail.wordpress.com/2013/02/05/android-phonegap-notificationsnotification-bar-from-a-backg… […]

  2. pari says:

    hello thanks for this tutorial , but i am having some problems in implementing it please help

    i made a new package ‘com.phonegap.plugin.localnotification’ in the src as told by you and included all the java files in it but am getting error in my java files because of which i am not able to run my application

    ERRORS
    1. in AlarmReceiver: line 73: final Notification notification = new Notification(R.drawable.ic_launcher, tickerText,
    System.currentTimeMillis());
    what changes do i have to implement in here

    2. i am getting a lot of errors in my LocalNotification.java files ..i mean a lot….could u please post the updated LocalNotification.java file..i really need it ..

    3. i wanted to ask do i have to make any changes in LocalNotification.js if yes then please tell

    i am using phonegap 2.7.0.
    my index.file looks like this:

    document.addEventListener(“deviceready”, appReady, false);

    function appReady() {

    if (typeof plugins !== “undefined”) {

    var now = new Date();
    now.setSeconds(now.getSeconds() + 90);

    plugins.localNotification.add({
    date : now,
    message : “Phonegap – Boooyyyaaaaah!\r\nUpyoass!”,
    ticker : “Yeeeaaaaahhhh!!!”,
    repeatDaily : false,
    id : 4
    });
    }
    };

    please help me …waiting for your reply eagerly..
    than you in advance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s