how to implements code for receiving a alert message? - android

hi all how to implements code for displaying alert message that alert message is when system time and our given time is same then it display a message as alert("you have a new message").if our given time is 04:22:00 when system time also same as our given time then receive message as alert.so kindly help any one of you to solve this problem

You'll need an AlarmManager to wake up the system in the exact moment:
long triggerAtTime = 0;
try {
triggerAtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2011-07-12 14:00:00").getTime();
} catch (ParseException e) {
}
Intent intent = new Intent(this, TestReceiver.class);
PendingIntent intentToSend = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, intentToSend);
And a BroadcastReceiver:
public class TestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: notify the user
}
}
And some XML in your manifest file:
<receiver android:name=".TestReceiver"></receiver>
In the onReceive function you can create a Toast or a status bar Notification:
http://developer.android.com/guide/topics/ui/notifiers/index.html

Related

Alarmmanager going off on reboot...but its set for 7 days ahead?

I'm failing to see why this alarm is going off on a reboot...I am setting it 7 days ahead here -
Intent intent = new Intent(MainActivity.this, Reminder.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MainActivity.this, 1, intent, 1);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
try {
am.cancel(pendingIntent);
} catch (Exception e) {
System.out.println("Derp");
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 7);
long time = calendar.getTimeInMillis();
am.set(AlarmManager.RTC_WAKEUP, time,
pendingIntent);
Here is my manifest that I have set for alarm to stick around on a reboot - Reminder is the class receiving the alarm-
<receiver android:name="com.practicum.notifications.Reminder" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
By default, all alarms are canceled when a device shuts down. To prevent this from happening, you can design your application to automatically restart a repeating alarm if the user reboots the device. This ensures that the AlarmManager will continue doing its task without the user needing to manually restart the alarm.
You have to manually reset the alarm once again in Bootup Receiver
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Set the alarm here.
}
}
All alarms are shut off when you power off the Android device.
You need to call setRepeating method
public class AlarmReceiver extends BroadcastReceiver {
private static final int PERIOD=5000;
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
static void scheduleAlarms(Context ctxt) {
AlarmManager am = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, YourService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
}
Check this answer from CommonsWare.
For future reference, I misunderstood how receving the boot complete action worked. I had the intent filter in both of my receiver classes so they were both running, when instead I needed an intent filter on a new broadcastreceiver class to RESET my alarmmanagers.

One time alarm not working

I have done some research and tried to implement a one time alarm that sends a notification to the user, but for some reason I cannot understand, when the time comes, the alarm is not being activated. I think the onReceive method is not being called, but I don't know why, since it's the first time I try to implement an alarm.
=== Edit: it seems that the alarm's onReceive is working after all, I got the toast message "Alarm!!" at the right time (don't know why it didn't the first time I tested), but no notification was received, though... Any clues?
This is the code for the Alarm class:
public class Alarm extends BroadcastReceiver {
public static final String PREFS_FILE_NAME = MainActivity.PREFS_FILE_NAME;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// send notification
Toast.makeText(context, "Alarm!!", Toast.LENGTH_SHORT).show();
// API < 16 so have to use compat
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setContentTitle(context.getResources().getString(R.string.memo_test_ready))
.setContentText(context.getResources().getString(R.string.click_to_start));
Intent resultIntent = new Intent(context, UpcomingTest.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(UpcomingTest.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(123, mBuilder.build());
}
public void Set(Context context)
{
DatabaseHandler db = new DatabaseHandler(context);
MemoryTestLevel memoTestLevel = new MemoryTestLevel();
long timeInterval;
long memoryTest_dateTime;
String alarmMemoLevel;
List<Phrase> studyPhrasesList = db.getPhrasesWithState(Phrase.START_STUDYING);
if (studyPhrasesList.size() > 0 ){ // if there are any phrases here, update them; dateTime == level 1
alarmMemoLevel = "Level 1 ";
memoTestLevel = db.getMemoryTestLevelWithLevel(MemoryTestLevel.LEVEL_1);
timeInterval = memoTestLevel.getTimeInterval();
TestDateTimeCalculator datetimeCalc = new TestDateTimeCalculator();
memoryTest_dateTime = datetimeCalc.calculate(timeInterval);
for(Phrase phrase : studyPhrasesList){
phrase.setMemoryTestPending(memoTestLevel.getMemoryTest_id(), memoryTest_dateTime);
db.updatePhrase(phrase);
}
} else {
// if there are no phrases to be set at level 1, then get the lowest memoTest_datime of
// the ones that are pending
alarmMemoLevel = "next after L1 ";
memoryTest_dateTime = db.getLowestMemoTestDateTime();
}
/* 2. Set new Alarm
* 2.1. Determine which phrases will go into this new alarm */
List<Phrase> nextMemoryTestPhrases = db.getNextMemoryTestPhrases(memoryTest_dateTime);
for(Phrase phrase : nextMemoryTestPhrases) {
phrase.setState(Phrase.MEMORY_TEST_SCHEDULED);
db.updatePhrase(phrase);
}
// 2.3 set alarm for required dateTime
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Alarm.class);
PendingIntent pendingInt = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP, memoryTest_dateTime, pendingInt);
// 2.4 save the alarm.dateTime in the preferences so it can be used in the "upcoming test" activity
SharedPreferences preferences = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putLong("NEXT_TEST_DATETIME", memoryTest_dateTime);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(memoryTest_dateTime);
String nextTestDateStr = sdf.format(calendar.getTime());
Toast.makeText(context, "Alarm set to " + alarmMemoLevel + nextTestDateStr, Toast.LENGTH_LONG).show();
editor.commit();
}
public void Cancel(Context context)
{
Intent intent = new Intent(context, MyBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
And I have a broadcast receiver in case the phone is rebooted:
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String PREFS_FILE_NAME = MainActivity.PREFS_FILE_NAME;
#Override
public void onReceive(Context context, Intent intent) {
// TODO setup alarm again (get datetime from system)
Alarm alarm = new Alarm();
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
SharedPreferences preferences = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
long nextTestDateInMillis = preferences.getLong("NEXT_TEST_DATETIME", 0);
if(nextTestDateInMillis > 0){
alarm.Set(context);
}
}
}
}
From the research I found, it seems that something is missing/wrong in my manifest. This is what I have there:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
The below is inside application:
<receiver android:name="liliana.phrasememo.util.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:process=":remote" android:name="liliana.phrasememo.util.Alarm"/>
Also, if you see anything else that's wrong in my implementation of Alarm + Notification it would be brilliant to give me the heads up. Thank you very much :-)
to set alarm may be this code helps you
Intent myIntent = new Intent(yourcontext, Alarm.class);
PendingIntent pendingIntent = PendingIntent.getService(act, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)act.getSystemService(act.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE,22);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
also you must implement service instead of broadcastreciever to run at alarm time
Thanks very much to answer posted here, what is missing in my code is the notification icon, which I have added like this:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher) // this was missing
.setContentTitle(context.getResources().getString(R.string.memo_test_ready))
.setContentText(context.getResources().getString(R.string.click_to_start));
And in fact, if we look at the documentation, it does specify that the small icon must be in the notification:
Required notification contents
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
The LogCat does have a file not found error:
05-05 12:39:39.191: A/NetworkStats(89): Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
But it doesn't cause any crashes so you might not realise it. I'm not sure anything could be added to the notification constructor itself that would allow the user to see right away that something is missing. I don't have very advanced Java knowledge.

AlarmManager never returns and event for the BroadcastReceiver, how to debug?

The code below does not throw any errors, nor does it work. When I debug the addInvoiceReminder() method it appears the time is being setup correctly and the AlarmManager is set to go off at the time previously set. Can someone see my flaw? I am not sure why the BroadcastReceiver's onRecieve event never fires.
//---adds an invoice reminder when the user successfully adds a sales or expense invoice---
public void addInvoiceReminder () {
//---gets a Calendar object with current time---
Calendar cal = Calendar.getInstance();
//---sets the calendar object to the reminder dialog date---
//cal.set(reminder_year, reminder_month, reminder_day);
cal.add(Calendar.SECOND, 30);
Intent intent = new Intent(this, DueInvoiceAlarmReceiver.class);
intent.putExtra("reminder", "Invoice Number: 999999 is due!");
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
//---gets the alarm manager service set for the calendar time which is the reminder time---
AlarmManager alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm_manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
//---Receives the event fired when the reminder date for an invoice is passed---
public class DueInvoiceAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("reminder");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
Make sure you declare your broadcast reciever in your manifest.
Try Calendar cal = cal .getInstance(); cal.setTimeInMillis(System.currentTimeMillis());
Because you are trying to receive the time in mill but never set it too it.

Problem retrieving intent extra

I have the following code for a one off alarm...
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(CalendarViewActivity.this, OneShotAlarm.class);
Bundle bun = new Bundle();
bun.putString("data", "hello this is my message...");
intent.putExtras(bun);
PendingIntent sender = PendingIntent.getBroadcast(CalendarViewActivity.this,
0, intent, 0);
// We want the alarm to go off 5 seconds from now. TODO
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
return false;
}
});
}
public class OneShotAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO
Toast.makeText(context, "Alarm! " + intent.getExtras().getString("data"), Toast.LENGTH_SHORT).show();
}
}
The alarm correctly goes off, but the "data" extra isn't getting retrieved for some reason, and is being set to null.
Thanks for the help!
Try:
Intent intent = new Intent(CalendarViewActivity.this, OneShotAlarm.class);
intent.putExtra("data", "hello this is my message...");
PendingIntent sender = PendingIntent.getBroadcast(CalendarViewActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Possible duplicate of getExtra from Intent launched from a pendingIntent
If that doesn't help, please tell us a bit more about your files (you need to have an activity where you set up the alarm, a broadcastreceiver that starts a service, and the service where you tell the app what to do when the alarm goes off)
Citation from the doc for putExtra function:
name The name of the extra data, with package prefix.
Couldn't it be the reason?

Alarm only triggers when I'm in the Activity that set it

I'm creating an alarm in my app from the ItemEdit Activity. Its where one can edit/view their note/todo item, they can also set a reminder/alarm for the item there. I set the alarm with the following code:
private void createAlarm() {
Intent intent = new Intent(this, ReminderReceiver.class);
intent.putExtra("reminder_message", "Reminder Received!");
intent.putExtra("item_id", mRowId);
PendingIntent sender =
PendingIntent.getBroadcast(
getApplicationContext(),
ALARM_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// Set alarm to the time given by the user.
am.set(AlarmManager.RTC_WAKEUP, mReminderCal.getTimeInMillis(), sender);
}
And here is the Receiver
public class ReminderReceiver extends BroadcastReceiver {
private static final String TAG = "MyApp";
#Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("reminder_message");
Log.v(TAG, message);
} catch(Exception e) {
Log.v(TAG, "OH SNAP!");
e.printStackTrace();
}
}
Edit: Also I have the following in my manifest:
<receiver android:process=":remote" android:name="ReminderReceiver"></receiver>
If I stay in the Activity where I set the alarm it is received fine. If I hit the back button to return to my ListActivity where all the items are listed or leave the app entirely the alarm never triggers. Have I done something wrong in setting up my alarm that it only triggers from the Activity that set it?
Thanks.
You need to look into a Service instead of an Activity for a long-living process that doesn't interact with the user (like an alarm clock).

Categories

Resources