I want the notification to be shown after every 4 hours after the Activity is Destroyed.
Here's my code snippet of main activity's onDestroy().
#Override
protected void onDestroy() {
Intent notificationIntent = new Intent(this, Notification.class);
PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(contentIntent);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 1000*00*00*04, contentIntent);
}
and here is my Notification.class code snippet:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class Notification extends Service {
#Override
public void onCreate() {
super.onCreate();
Intent mainIntent = new Intent(this, Main.class);
NotificationManager notificationManager
= (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
android.app.Notification noti = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("Title")
.setContentText("It's been so Long!!!")
.setSubText("Please return back to App")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {1000,1000,1000,1000})
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Important Notification")
.setWhen(System.currentTimeMillis())
.build();
notificationManager.notify(0, noti);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
I am working on this since so many days but I am unable to complete the task.
Any Help would be highly Appreciated.
Thanks in Advance!
HELP please!!!
You're multiplying by 0 here:
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
System.currentTimeMillis(), 1000*00*00*04, contentIntent);
The third parameters is the "interval in milliseconds between subsequent repeats of the alarm", so your alarm will be only be fired once because the interval is, well, zero. You need to change the third parameter to four hours, which in milliseconds translates to 3600 * 1000 * 4.
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
System.currentTimeMillis(), 3600 * 1000 * 4, contentIntent);
Related
I would like to create two different notifications (with different title, text, content...etc.) and issue them at two different time of the day.
That's my MainActivity code:
First notification:
receiver.putExtra("which", 0);
PendingIntent pendingIntent = PendingIntent.getBroadcast(CountdownActivity.this, 0, receiver,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, after30minutes, pendingIntent);
Second notification:
receiver.putExtra("which", 1);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(CountdownActivity.this, 0, receiver,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC_WAKEUP, (endInSeconds*1000)-(1800*1000), pendingIntent2);
receiver is an intent between this class and receiver class (that extends broadcast receiver).
That's my NotificationReceiver (extends BroadcastReceiver) code:
#Override
public void onReceive(Context context, Intent intent)
{
Intent intentService = new Intent(context, NotificationService.class);
context.startService(intentService);
}
Finally, that's my NotificationService (extends Service) code:
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
//preparazione variabili
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
countdown = new Intent(this.getApplicationContext(), CountdownActivity.class);
pendingIntent = PendingIntent.getActivity( this.getApplicationContext(),0, countdown,PendingIntent.FLAG_UPDATE_CURRENT);
//costruzione notifica
if(intent.getExtras().getInt("which") == 0) //1 ora
{
notification = new Notification.Builder(getApplicationContext())
.setAutoCancel(true)
.setContentTitle("1 ora")
.setContentText("contenuto")
.setLargeIcon(bm)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setLights(Color.BLUE, 3000, 3000)
.setContentIntent(pendingIntent)
.build();
}
else if(intent.getExtras().getInt("which") == 1) //mezz'ora
{
notification = new Notification.Builder(getApplicationContext())
.setAutoCancel(true)
.setContentTitle("Ole")
.setContentText("contenuto")
.setLargeIcon(bm)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setLights(Color.BLUE, 3000, 3000)
.setContentIntent(pendingIntent)
.build();
}
//operazioni finali
countdown.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
EDIT
I solved putting a countdown in my NotificationService class.
Where you call notificationManager.notify(0, notification);, you should pass a unique ID instead of 0. So, for instance, it would be sufficient to pass the value of intent.getExtras().getInt("which"). Mostly, I declare these IDs as a public static final int in the class.
As the docs state for NotificationManager#notify(int, android.app.Notification):
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
http://developer.android.com/reference/android/app/NotificationManager.html
Updated MyService #CommonsWare
i have a service that if started will set up an alarm that triggers the notification.
This works fine and the alarms are canceled if the service is stopped.
i am trying to get the notification to open a new activity class but can not get it done
my service class is the following:
package com.example.andtip;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class BReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, DoSomething.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent("com.example.andtip"),0 );
PendingIntent pi2 = PendingIntent.getActivity(context, 0, myIntent,0 );
myNotification=new NotificationCompat.Builder(context)
.setContentTitle("This is a notification from the example alarm application.")
.setContentText("Notification")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
how should i link the intent pi2 to the notification?
i am trying to get the notification to open a new activity class but can not get it done
You are using getBroadcast() to create your PendingIntent. Use getActivity() to create a PendingIntent that starts up an activity. Make sure that the Intent you put in the PendingIntent is for an activity, and make sure that the activity has its entry in the manifest.
I have set up a notification which will be shown 4 hours after the App being destroyed.
But as I am destroying the App, the notification is coming immediately and also after 4 hours.
Here's my Main Activity's onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
}
and here's my AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent mainIntent = new Intent(context, Main.class);
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
android.app.Notification noti = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("Title")
.setContentText("It's been so Long!!!")
.setSubText("Please return back to App & Learn more Duas.")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {700,700,700,700})
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Important Notification")
.setWhen(System.currentTimeMillis())
.build();
notificationManager.notify(0, noti);
}
}
I want that Notification should be shown after every 4 hours & not immediately of App being destroyed.
Any help would be highly Appreciated.
Thanks in Advance.
It is because of small mistake
just change this line
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
TO this
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+(3600*1000*4)), 3600*1000*4, pendingIntent);
I am using this notifications code:
package com.example.mega;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Tech";
CharSequence message = "Check out our NEW COLLECTION !!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
"Check out our NEW COLLECTION !!" , System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
As you see I haven't yet added AlarmManager since I have no experience using it ,I am new to android.What should I add to the code to have show the notification every 24 hours ??
Calendar calendar = Calendar.getInstance();
// 8.00 (8 AM)
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0 , new Intent(context, Your_Class.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
This sets an alarm everyday at 8.00 AM
Or you can use https://github.com/commonsguy/cwac-wakeful. Take a look at the documentation on the link.
Take a look at this: Fire notification at every 24 hours and at exact time of 8 AM
And this: http://blog.blundellapps.com/notification-for-a-user-chosen-time/
Trying to convert my iOS app to android, I know I can't port it so I wrote it from scratch
How can I covert this notification to Android Java code?
-(IBAction)turnon {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:28];
[comps setMonth:9];
[comps setYear:2012];
[comps setHour:8];
[comps setMinute:25];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *fireDate = [gregorian dateFromComponents:comps];
UILocalNotification *alarm = [[UILocalNotification alloc] init];
alarm.fireDate = fireDate;
alarm.repeatInterval = NSDayCalendarUnit;
alarm.soundName = #"msl.aiff";
alarm.alertBody = #"This is a message..";
alarm.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:alarm];
I've searched the web for like 4 hours now and I think this is simple for an Android developer but since I just started I just don't have any idea how to do this.
Any help is really appreciated!
This is what your looking for:
You can use the alarm manager to show notifications at specific times, even when your app is not running at all.
http://developer.android.com/reference/android/app/AlarmManager.html
Everyday notifications at certain time
This one is useful to:
Using Alarmmanager to start a service at specific time
Edit see comments:
You can the AlarmManager for this, first create you self some kind of reciever.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, MyService.class);
context.startService(dailyUpdater);
Log.d("AlarmReceiver", "started service");
}
}
Than you need to create the service which is going to show the notifications
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = 546;
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
#Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Toast.makeText(this, "show notification", Toast.LENGTH_SHORT).show();
//notification code here
}
}
And finally you need to set the alarm:
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 30);
Intent open = new Intent(context, AlarmReceiver.class);
open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, open, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, 10000, pendingIntent);
}
And before you make a test run add your Receiver and Service to your manifest file:
<service android:name=".MyService"></service>
<receiver android:name=".AlarmReceiver"></receiver>
A copy paste with some minor changes from the Android developer site
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
// Sets an ID for the notification, so it can be updated
int mId= 1;
mNotificationManager.notify(mId, mBuilder.build());