push notification repearting for every second - android

Hi guys i am trying to create the push notification using the alarm manager where push notification must come at morning 8AM everything is good but notification is also coming but after 8AM notification is completed the notification coming when ever i open the App or clear from recents or for every one hour notification is coming please help me out facing this problem from last 1 Week
MainActivity.class
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationintent = new Intent(this, Notify.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, notificationintent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationintent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
Calendar calnotify = Calendar.getInstance();
Calendar now=Calendar.getInstance();
//Time Alaram manager
calnotify.set(Calendar.HOUR_OF_DAY, 10);
calnotify.set(Calendar.MINUTE, 00);
calnotify.set(Calendar.SECOND, 0);
if (now.after(calnotify)){
calnotify.add(Calendar.DATE,1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, calnotify.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Notify.class
//BroadCastReceiver class
public class Notify extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent pushservice=new Intent(context,PushNotification.class);
pushservice.setData((Uri.parse("custom://"+System.currentTimeMillis())));
context.startService(pushservice);
}
}
PushNotification.class
public class PushNotification extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Resources resources = getResources();
getnotify(resources);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Resources resources = getResources();
getnotify(resources);
/*Notify notify=new Notify();
notify.abortBroadcast();*/
}
private void getnotify(Resources resources) {
Bitmap icon = BitmapFactory.decodeResource(resources,
R.drawable.sr_notification_icon);
PugNotification.with(this)
.load()
.title(getResources().getString(R.string.app_name))
.message("Latest Chitka")
.bigTextStyle(getResources().getString(R.string.app_name))
.smallIcon(getNotificationIcon())
.largeIcon(icon)
.flags(android.app.Notification.DEFAULT_ALL).autoCancel(true).click(MyCalendarActivity.class)
.simple()
.build();
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.sr_icon : R.drawable.sr_notification_icon;
}
}

Looks like the code for setting alarm is executing multiple times as it is called from the main Activity of the application. You should set a flag that gets set to true once the alarm is set. Next time skip the alarm setting based on this flag.

Related

Check server for notifications for app and display them if present

I am creating an application on Android which has a MySql server. I want a notification if there is any data present in the File (The User has the job to remove it all but after verifying them). So, I need a good background worker which activates after one hour, checks if any data is there, send a notification, close itself and then again activate after one hour. The time one hour can be changed. I use a AsyncTask for downloading(Unavoidable). I am good at sending notifications and using AsyncTask.
I am a bit lazy so have not done any experiment before verifying that it will complete my task.
I think it may use the Service class. Please provide detailed information. Please give a whole tutorial when telling to use any Github Library cause I am new to Github.
Thank You,
Yours Respectfully,
India's youngest android application developer
I found out the solution Myself and so decided to help out any other new Programmer. Here it is-
AlarmReceiverLifeLog.java
public class AlarmReceiverLifeLog extends BroadcastReceiver {
private static final String TAG = "LL24";
static Context context;
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Alarm for LifeLog...");
Intent serviceIntent = new Intent(context,MyReciever.class);
context.startService(serviceIntent);
}
}
MyReciever.java
public class MyReciever extends Service {
int mStartMode;
IBinder mBinder;
boolean mAllowRebind;
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Your Method to get Data from Server
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
}
#Override
public void onDestroy() {
}
//method to show notification to be called when you finally decide that you have to notify the user
public void showNotification(String title,String message){
Log.d("Service","Going to show notification");
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(title)
.setContentText(message);
Intent notificationIntent = new Intent(this, NavigationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Add this in your AndroidManifest.xml
<receiver android:name=".AlarmReceiverLifeLog" >
</receiver>
<service android:name=".MyReciever" />
Activating the reciever
Intent ll24 = new Intent(this, AlarmReceiverLifeLog.class);
PendingIntent recurringLl24 = PendingIntent.getBroadcast(this, 0, ll24, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, 0, AlarmManager.INTERVAL_HALF_DAY, recurringLl24);//For waking it after each 12hrs.

Why Background Service stops working when app is closed?

I am trying to create a background service that will be called every ten minutes, perform a task and this should not be killed when the application is closed.
The following is the code snippet:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_service);
Intent intent = new Intent(this, AlarmReceiverLifeLog.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10 * 60 * 1000, pendingIntent);
}
In onCreate, it will call the AlarmReceiverLifeLog class every ten minutes. The following is the code for AlarmReceiverLifeLog class:
public class AlarmReceiverLifeLog extends BroadcastReceiver {
static Context context;
#Override
public void onReceive(Context context, Intent intent) {
Intent ll24Service = new Intent(context, LifeLogService.class);
context.startService(ll24Service);
}
}
public class LifeLogService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(), this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
Calendar calendar = Calendar.getInstance();
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis() + 100, restartServicePI);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I am not able to figure out what I have missed. When I close the app the background services is getting killed.
Can anyone suggest anything regarding this?
when the app is closed the service get closed also because they are in a one thread, so the service should be on another thread in order fot it not to be closed, look into that and look into keeping the service alive with alarm manager here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

I want to fire the notification with particular date time in android

In my Application I have Multiple events for every event I need to create one UILocalNotification for example like I want to say wishes on Fathers day,Mothers and some festivals. So I already I have the specific date now I want to fire it on the particular day please how to do this. I have already done for single UILocalNotification. Now I need for multiple fire dates.
If I comment the date it's firing on particular time. Now date with time is not working.
Now problem how to add multiple dates and time in same activity I want to fire the notifications.
Can anyone please help me.
MyView class
public class MyView extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar firingCal = Calendar.getInstance();
firingCal.set(Calendar.MONTH, 7);
firingCal.set(Calendar.YEAR, 2014);
firingCal.set(Calendar.DAY_OF_MONTH, 9);
firingCal.set(Calendar.HOUR_OF_DAY, 16);
firingCal.set(Calendar.MINUTE, 35);
firingCal.set(Calendar.SECOND, 0);
// MyView is my current Activity, and AlarmReceiver is the
// BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyView.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
* The following sets the Alarm in the specific time by getting the long
* value of the alarm date time which is in calendar object by calling
* the getTimeInMillis(). Since Alarm supports only long value , we're
* using this method.
*/
alarmManager.set(AlarmManager.RTC_WAKEUP, firingCal.getTimeInMillis(),
pendingIntent);
}
}
MyAlarmService class
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}

How to create a background notification

I want to implement a Service which permit to show a notification (daily, or after XX minutes) even if I close the application. (Actually, when I press back button, I finish the MainActivity...)
I need a runnable notification even if I didn't start the application (after rebooting the device for example, of course when the trigger is declanched)...
I tried some clear examples and tutorials but I doesn't find what I need.
Please HELP!
Thanks in advance,
Mohamed
You can do it with alarm manger:
public class AlarmHelper {
private Context context;
private AlarmManager alarmManager;
private static final String TAG = "AlarmHelper";
public final static String ALARM_ALERT_ACTION = "com.android.alarmclock.ALARM_ALERT";
public AlarmHelper(Context context) {
this.context = context;
alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
}
public void setNotifyAlarm(Long milliSecond) {
PendingIntent pendingIntent = getNotifyPendingIntent();
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, pendingIntent);
// alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, sender);
}
public void cancelNotifyAlarm() {
PendingIntent pendingIntent = getNotifyPendingIntent();
alarmManager.cancel(pendingIntent);
}
private PendingIntent getNotifyPendingIntent() {
Intent intent = new Intent(context, AlarmExpireService.class);
return PendingIntent.getService(context, 0, intent, 0);
}
public void setExpireAlarm(int minute) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, minute - 1);
PendingIntent pendingIntent = getExpirePendingIntent();
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
}
public void cancelExpireAlarm() {
PendingIntent pendingIntent = getExpirePendingIntent();
alarmManager.cancel(pendingIntent);
}
private PendingIntent getExpirePendingIntent() {
return PendingIntent.getService(context, 0, new Intent(context,
AlarmExpireService.class), 0);
}
}
Now in the AlarmExpireService.java:
public class AlarmExpireService extends Service {
// private static final String TAG = "AlarmExpireService";
private static final String TAG = "AlarmExpireService";
#Override
public void onCreate() {
super.onCreate();
//your logic for start activity or generate notification.
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AppLog.Log(TAG, "On start command");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Now Register service in the manifest file:
<service android:name="your_package.AlarmExpireService" />
For just call a method from AlarmHelper's setNotifyAlarm method and your work is done pass the time in millisecond (it will start after that time and notification will be pop up).
For more information take a reference of this links:
1. AlarmManager
2. Service
3.Pending Intent

BroadcastReceiver not triggered by Alarm

I am trying to set up an alarm that will run in the background and trigger (eventually) a save event. At the moment I simply have this code attached to a button. Press the button and the alarm should start leaving Toast messages behind as an indication that it is functioning. At the moment everything runs except the onReceive in the BroadcastReceiver is never triggered.
Here is my code:
The class setting up the alarm:
//FIXME - rename (ie BackgroundSave; more descriptive)
public class AlarmReceiver extends Service{
//FIXME - make sure you kill the service
public void onCreate() {
super.onCreate();
Toast.makeText(getApplication().getApplicationContext(), "Service onCreate called", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplication().getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show();
setAlarm(AlarmReceiver.this);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
public void setAlarm(Context c) {
AlarmManager alarmManager = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(c, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(c, 0, i, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 1000, 1000, pi);
Toast.makeText(c.getApplicationContext(), "setAlarm called", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Here is the BroadcastReceiver:
public class Alarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm", Toast.LENGTH_SHORT).show();
}
}
And here is my manifest:
<!-- Alarm -->
<service android:name="com.xxxx.android.tools.AlarmReceiver" android:enabled="true" />
<receiver android:name="com.xxxx.android.tools.Alarm" ></receiver>
The alarm onReceive is never triggered.
You have to use android.os.SystemClock.elapsedRealtime() as your base time when using AlarmManager.ELAPSED_REALTIME_WAKEUP.
That said i think to use the AlarmManager for your saving purpose is not the best approach. The alarm manager is pretty heavyweight. You should consider using a simple Handler to trigger your save action.
Have a look at Handler.postAtTime().

Categories

Resources