Notifications didn't show up at specified time - java

What's wrong with this scrap of code? It should came up with an notification at specified time. I have done some testing and logging, but nothing has changed - notifications has never showed up...
NotificationService.java
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
public class NotificationService extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String link = "http://www.login.lt/apdovanojimai/";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setContentTitle("LOGIN 2015")
.setContentText(getResources().getString(R.string.rate_at_login))
.setSmallIcon(R.drawable.logo)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
}
}
setAlarm():
private void setAlarm() {
Intent myIntent = new Intent(this , NotificationService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
Calendar date1 = Calendar.getInstance();
date1.set(2015, 04, 16, 19, 00, 00);
Calendar date2 = Calendar.getInstance();
date2.set(2015, 04, 24, 19, 00, 00);
alarmManager.set(AlarmManager.RTC_WAKEUP, date1.getTimeInMillis(), pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, date2.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000 , pendingIntent);
}
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
setAlarm();
}

Considering setAlarm() method is in YourActivity:
private void setAlarm() {
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(YourActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 23);//set the hour which you want
cal.set(Calendar.MINUTE, 56);// set the minute
cal.set(Calendar.SECOND, 0);// set seconds
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
In AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
Context myContext;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
myContext = context;
showNotification();
}
public void showNotification()
{
String link = "http://www.login.lt/apdovanojimai/";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(link));
PendingIntent pIntent = PendingIntent.getActivity(myContext, 0, intent1, 0);
NotificationCompat.Builder n = new NotificationCompat.Builder(myContext)
.setContentTitle("LOGIN 2015")
.setContentText("hello")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) myContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
}
}
Make sure you add this in your manifest file:
<receiver android:name=".AlarmReceiver" />

Related

AlarmManager not Starting Service

Before, the alarm manager was working. I don't think I changed anything, but now it isn't starting at all.
Here is the code where I set the alarm manager:
SettingsActivity.java
Intent intent;
static PendingIntent recurringDownload;
intent = new Intent(context, UpdateScoresService.class);
recurringDownload = PendingIntent.getService(context, 0, intent, 0);
Preference.OnPreferenceChangeListener refreshListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("1")){ /* daily */
background_refresh.setSummary("Scores will be refreshed daily.");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownload);
recurringDownload.cancel();
Log.e("DAILY REFRESH", " ");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE,00);
if(calendar.before(Calendar.getInstance())){
Log.e("AFTER", "10 AM DAILY");
calendar.add(Calendar.DATE, 1);
}
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}else if(newValue.toString().equals("2")){ /* weekly */
Log.e("WEEKLY REFRESH", " ");
background_refresh.setSummary("Scores will be refreshed weekly.");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownload);
recurringDownload.cancel();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE,00);
if(calendar.before(Calendar.getInstance())){
Log.e("AFTER", "10 AM WEEKLY");
calendar.add(Calendar.DATE, 1);
}
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, recurringDownload);
}else{ /* manually */
background_refresh.setSummary("Scores will be refreshed manually.");
Log.e("MANUAL REFRESH", " ");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownload);
recurringDownload.cancel();
}
return true;
}
};
The UpdateScoresService is here:
public class UpdateScoresService extends IntentService {
public int countChanged;
Context context = this;
public UpdateScoresService() {
super("UpdateScoresService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.e("onHandleIntent", "grabbing scores");
countChanged = new GetAnimeScores(getApplicationContext()).refreshScores();
if(countChanged>0){ //Display notification if any scores changed
Log.d("Creating notification", " ");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_timeline_white_24dp);
builder.setContentTitle("MAL Score Tracker");
builder.setAutoCancel(true);
if(countChanged==1){
builder.setContentText("1 score changed since you were gone!");
}else{
builder.setContentText(countChanged+" scores changed since you were gone!");
}
Intent intent1 = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent1);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
}
}
}
}
The Log in the SettingsActivity print but the Log in the onHandleIntent from the Service do not print. I'm not sure what is wrong.
It is better to have a BroadcastReceiver which will be responsible for starting the service. The code for it should look something like this:
Create a BroadcastReceiver class:
public class ReceiverToStartService extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, UpdateScoresService.class);
ComponentName service = context.startService(i);
}
}
Register receiver in your Manifest:
<receiver android:name=".ReceiverToStartService"/>
Now change the Intent in your Activity that you are passing to PendingIntent:
intent = new Intent(context, ReceiverToStartService.class);
recurringDownload = PendingIntent.getService(context, 0, intent, 0);

Android: How to create a reminder such as google keep reminder

I want to add a reminder to my android app such as Google Keep app reminder for notes, as you know in Gkeep you can set reminder for your notes by set date (Today,Tomorrow,Next same day or Pick a date from Calendar) and set time (Morning, Afternoon,Evening, Night or pick a time from Clock).
Any help?
I found my answer! and share it with you because i think its nothing to do with Mechanical Turk :)).
in MainActivity:
final AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
final Intent intentAlarm = new Intent(MainActivity.this, AlarmReceiver.class);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 22);
calendar.set(Calendar.HOUR, 5);
calendar.set(Calendar.AM_PM, Calendar.PM);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 6);
calendar.set(Calendar.YEAR,2015);
long when = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP,when, PendingIntent.getBroadcast(MainActivity.this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
and the AlarmReciver class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Calendar now = GregorianCalendar.getInstance();
Notification.Builder mBuilder =
new Notification.Builder(context)
.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("my title")
.setContentText("my text");
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.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(1, mBuilder.build());
}
}
And to cancel the reminder :
if (alarmManager!= null) {
alarmManager.cancel(PendingIntent.getBroadcast(MainActivity.this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}

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