Alarm with notification, notification wont pop up - java

So I don't know why this code is not working. I wanted to make an "alarm" notification that would go off once a day. Just wanted to say I'm new to android. Changed up the code a bit couple of times but still wont work.
Alarm method executes notification does too but I get this : -248/? D/PowerManagerService﹕ releaseWakeLock flags=0x1 tag=AlarmManager W/ActivityManager﹕ Unable to start service Intent { flg=0x4 cmp=com.example.polakken.test/.lol (has extras) }: not found 06-13 00:00:00.825 231-267/? D/PowerManagerService﹕ acquireWakeLock flags=0x1 tag=AlarmManager 06-13 00:00:00.825 231-248/? D/PowerManagerService﹕ releaseWakeLock flags=0x1 tag=AlarmManager
My Code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int i = preferences.getInt("numberoflaunches", 1);
if (i < 2) {
alarmMethod();
i++;
editor.putInt("numberoflaunches", i);
editor.commit();
}
if (savedInstanceState == null) {
splashMethod();
}
}
//...
private void alarmMethod() {
Intent intentbro = new Intent(this, lol.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intentbro, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
Toast.makeText(MainActivity.this, "start alarm", Toast.LENGTH_LONG).show();
}
//notification class
public class lol extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent1, 0);
b.setContentText("lol");
b.setContentTitle("Default notification");
b.setSmallIcon(R.drawable.iconography_small_size);
b.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
}
}

You are creating the PendingIntent with PendingIntent.getService(), but you are supplying an Intent with an Activity.
So for your code to work you would need to use PendingIntent.getActivity().
(Additionally you have to add the corresponding <activity> tag to your AndroidManifest.xml.)
However, this is probably not exactly what you want: The only thing the lol Activity does is adding a notification. You might want to use a BroadcastReceiver (or perhaps a WakefulBroadcastReceiver) instead. In this case you would need to use PendingIntent.getBroadcast() instead of getActivity().

Follow these steps
1Create an Activity and add this code to setAlarm(can be any name)
Suppose you want to set Alarm for 24/02/15 ,14:00PM
#SuppressLint("UseSparseArrays")
public void setAlarms(Long id,String event_date,String event_time,Context context)
{
Calendar cal=Calendar.getInstance();
String[] parts=event_date.split("/");
String Event_date=parts[0];
String Event_month=parts[1];
String Event_Year=parts[2];
String[] parts1=event_time.split(":");
String Event_HOD=parts1[0];
String Event_MIN=parts1[1];
cal.add(Calendar.YEAR, Integer.parseInt(Event_Year)-cal.get(Calendar.YEAR));
cal.add(Calendar.MONTH, (Integer.parseInt(Event_month)-1)-cal.get(Calendar.MONTH));
cal.add(Calendar.DAY_OF_MONTH, Integer.parseInt(Event_date)-cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(Event_HOD)-cal.get(Calendar.HOUR_OF_DAY));
cal.add(Calendar.MINUTE, Integer.parseInt(Event_MIN)-cal.get(Calendar.MINUTE));
cal.add(Calendar.SECOND, 0);
AlarmManager am =(AlarmManager)context.getSystemService(Activity.ALARM_SERVICE);
//Your BroadcastReceiver which will receive Alarm
Intent intent = new Intent(context, AlarmReceiver.class);
//you can use PutExtra() to send additional parameter with Intent
//PendingIntent to add
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
(int)(long)id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
Toast.makeText(context, "alarm Set for Know", Toast.LENGTH_LONG).show();
}
2)Inside BroadcastReceiver onReceive() method
#Override
public void onReceive(Context context, Intent intent) {
//Receive parameter and do what you want to do with parameter
//Using RemoteViews you can Inflate a CustomLayout when user clicks on Notification when you do not want any CustomLayout for Notification remove it
RemoteViews contentView1 = new RemoteViews("com.example.new_reminder_book" , R.layout.custom_notification);
contentView1.setTextViewText(R.id.cn_tv_title, Event_title);
contentView1.setTextViewText(R.id.cn_tv_category, Event_category);
contentView1.setImageViewResource(R.id.cn_tv_image, R.drawable.event);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.appicon)
.setContent(contentView1)
.setAutoCancel(true)
.setOngoing(true);
//Target Activity that will start when you click on Notification
Intent result=new Intent(context, EmptyActivity.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(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(EmptyActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(result);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification=mBuilder.build();
notification.contentView=contentView1;
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify((int) System.currentTimeMillis(), notification);
//A mp3 fine in res->raw that will play when notification fire
MediaPlayer mp = MediaPlayer.create(context, R.raw.listen);
mp.start();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
/*Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
//Set pattern for Vibration
long[] pattern={2000,3000,4000};
vibrator.vibrate(pattern,1);*/
wl.release();
}
}
3)Declare Two permissions in Manifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.VIBRATE"/>
4)Declare You AlarmReceiver in Manifest.xml
<receiver android:name=".extra.AlarmReceiver" android:label="#string/title_activity_alarm_receiver" android:exported="true"> </receiver>
Follow these documents
http://developer.android.com/reference/android/content/BroadcastReceiver.html
http://developer.android.com/reference/android/app/AlarmManager.html
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
http://developer.android.com/reference/android/os/PowerManager.WakeLock.html
Hope this will help you

Related

How to set multiple alarms firing distinct notifications for each in Android

I am trying to develop an application in which the user can create more than 1 alarms for the same time ,say, 09:48. And for this time, each alarm has to create its own notification which leads the user to an activity when the notification is clicked. The other alarms which were scheduled at the same time must keep ringing until their notifications are clicked. Now, I am able to create alarms for different times and get their corresponding notifications which lead to an activity in which the user can dismiss or snooze the alarm. However, when I schedule more than one alarm for the same time, only 1 alarm is ringing and the other one gets lost. I share my code pieces at the below.
public void schedule(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(context, alarmId, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
alarmPendingIntent
);
In my broadcastReceiver class:
private void startAlarmService(Context context, Intent intent) {
Intent intentService = new Intent(context, AlarmService.class);
Log.println(Log.DEBUG, "DEBUG", "************Alarm Broadcast Receiver**********");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intentService);
} else {
context.startService(intentService);
}
}
In my AlarmService :
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
mediaPlayer.setLooping(true);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, RingActivity.class);
int requestCode = new Random().nextInt(Integer.MAX_VALUE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, notificationIntent, 0);
//String alarmTitle = String.format("%s Alarm", intent.getStringExtra(TITLE));
int notificationId = new Random().nextInt(Integer.MAX_VALUE);
Notification notification = new NotificationCompat.Builder(this, String.valueOf(notificationId))
.setContentTitle("PASS1")
.setContentText("PASS2")
.setSmallIcon(R.drawable.pill)
.setContentIntent(pendingIntent)
.build();
mediaPlayer.start();
long[] pattern = { 0, 100, 1000 };
vibrator.vibrate(pattern, 0);
startForeground(1, notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
vibrator.cancel();
}
in this code
startForeground(1, notification);
you are using 1 as the id.
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.
So the second alarm notification with the same id (because you are using a fixed value of 1) is replacing the old one

How to avoid continuous notification when notification is clicked

I want to send notification by BroadcastReceiver. Notification sent by AlarmReceiver but again sent notification when i clicked the notification. The same thing happens again, again and again like endless loop
Here is my AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
// This intent is fired when notification is clicked
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
// Notifcation notify sound
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Have a good weekend");
//Notification click after clear notification
builder.setAutoCancel(true);
//Set notification sound
builder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
}
and MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm();
}
private void setAlarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK,6);
calendar.set(Calendar.HOUR_OF_DAY,16);
calendar.set(Calendar.MINUTE,53);
calendar.set(Calendar.SECOND,0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
As on click on notification it open MainActivity and in onCreate method of this activity you are calling setAlarm() . So on click of notification onCreate method is invoked then setAlarm() is invoked , this again set Alarm and build notification.
Do following changes
call setAlarm() onClick of a button, so that it is not invoked automatically onCreate of activity.
If you want to send notification automatically
change the intent of notification
Intent i = new Intent(context, MainActivity.class);
As of now you are using intent to open ManinActivity on click of notification.
Change Intent to
Intent i = new Intent(context, OtherActivity.class);
OtherActivity is the activity which does not setAlarm() or build notification in onCreate method.
Alternative Method
Use sharedPreferences to check whether the notification is build once or not.
if build once then don't call setAlarm()

How to create a notification service?

Sorry if any of this kind of question has already been posted, i still didnt find the answer that I'm looking for.
My mission is simple - I want to create an app that pushes a notification excatly in 9PM.
Here's what I found and what I currently have -
Intent intent = new Intent();
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 6);
cal.set(Calendar.HOUR, 9);
cal.set(Calendar.AM_PM, Calendar.PM);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24 , pIntent);
Notification noti = new Notification.Builder(this)
.setTicker("Ticker Title")
.setContentTitle("Content Title")
.setContentText("Notification content.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
noti.flags=Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
I herd there has to be a kind of service to display the notification. How do I create it? If my code's wrong, feel free to re-make it.
Thanks a lot in advance!!
inside manifest
<service android:enabled="true" android:name=".NotifyIntentService" />
<receiver android:name=".AlarmReciever"/>
inside Activity
Intent intent = new Intent(this, AlarmReciever.class);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 6);
cal.set(Calendar.HOUR, 9);
cal.set(Calendar.AM_PM, Calendar.PM);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
inside main project
public class AlarmReciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context,
NotifyIntentService.class);
startService(serviceIntent);
}
}
intent service
public class NotifyIntentService extends IntentService
{
#Override
protected void onHandleIntent(Intent intent) {
//your notification code
//notify();
}
}
notification in all device

Dynamic notification from sqlite db

I've got a question for you. I want to use a notification service through BroadcastReceiver and AlarmManager. I set the alarm manager with a dynamic list of times from my db.
I use this method that i call on my MainActivity OnCreate(), but doesn't work
private void restartNotify() {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pendingIntent);
ArrayList<String> item = new ArrayList<String>();
item = GetLists.GetTimesListForNotification(this);
for (int i = 0; i < item.size(); ++i) {
String time = item.get(i);
int Position = time.indexOf(":");
int hour = Integer.parseInt(time.substring(0, Position));
int min = Integer.parseInt(time.substring(Position + 1));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
am.set(AlarmManager.RTC, cal.getTimeInMillis(),
pendingIntent);
}
this is my broadcast receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager mManager;
mManager = (NotificationManager) context.getApplicationContext()
.getSystemService(
context.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context.getApplicationContext(),
MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,
"Nuovo messaggio da cura alert", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context.getApplicationContext(),
"Le notifiche funzionano", "it is working",
pendingNotificationIntent);
mManager.notify(0, notification);
}
}
Thank you.
Well this is because your pending intents request code is same though you are running a loop. What you can do is get your pending intent intu your loop and set the request code i. This may work. Though it is late but this may help others

How to create a custom notification in android

I would like to create a custom notification service in my app.
I wouldn't use the google service (google cloud messaging).
Is there a way to create a daemon that check every X seconds a particular condition on my app db and show a notification?
Thank you,
edit
I call this method in MainActivity's oncreate(). I get the times from my db
private void restartNotify() {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pendingIntent);
ArrayList<String> item = new ArrayList<String>();
item = GetLists.GetTimesListForNotification(this);
for (int i = 0; i < item.size(); ++i) {
String time = item.get(i);
int Position = time.indexOf(":");
int hour = Integer.parseInt(time.substring(0, Position));
int min = Integer.parseInt(time.substring(Position + 1));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
am.set(AlarmManager.RTC, cal.getTimeInMillis(),
pendingIntent);
}
And this is my broadcast receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager mManager;
mManager = (NotificationManager) context.getApplicationContext()
.getSystemService(
context.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context.getApplicationContext(),
MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,
"New message to read", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context.getApplicationContext(),
"notification are work", "it's work",
pendingNotificationIntent);
mManager.notify(0, notification);
}
}
You can use AlarmManager + BroadcastReceiver like so:
private void setRecurringAlarm(Context context) {
Intent downloader = new Intent(this, MyStartServiceReceiver.class);
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, downloader, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 6000, 10000, pendingIntent);
}
BroadcastReceiver class:
public class MyStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do the stuff...
}
}
And don't forget to register receiver in your manifest:
<receiver android:name=".MyStartServiceReceiver"
android:enabled="true"/>
You have to use Alarm Manager to schedule code for execution every specific period. take a look here:
http://developer.android.com/training/scheduling/alarms.html

Categories

Resources