0

I working on alarm application. I tried to implement alarm notification and got notifications for every day but I need to set alarm for 7 days, after that it has to cancel. I cancelled it in broadcast receiver whenever seven days out, but still I'm getting notifications after seven days also.

public class MyTest extends AppCompatActivity {

    AlarmManager alarmManager;
    SharedPreferences preferences;

    SharedPreferences.Editor editor;
    PendingIntent pendingIntent;
    int RequestCode =777;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_test);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        AlarmReciever alarm = new AlarmReciever();
        //  alarm.setAlarm(this);
        int alarmId = 0;
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent alarmIntent = new Intent(MyTest.this, AlarmReciever.class); // AlarmReceiver1 = broadcast receiver
        alarmIntent.putExtra("alarmId", alarmId);
        pendingIntent = PendingIntent.getBroadcast(MyTest.this, RequestCode, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // alarmIntent.setData((Uri.parse("custom://" + System.currentTimeMillis())));

        Calendar alarmStartTime = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        alarmStartTime.set(Calendar.HOUR_OF_DAY, 00);
        alarmStartTime.set(Calendar.MINUTE, 00);
        alarmStartTime.set(Calendar.SECOND, 0);

        Log.d("Alarm", now.toString());
        /// int count= 0;
        // last i added for comparision
        if (now.after(alarmStartTime)) {
            //second
            Log.d("Alarm", "Added a day");
            alarmStartTime.add(Calendar.DATE, 1);
            // count++;

        }
        /*  System.out.println(count);
        if(count==7){
            alarmManager.cancel(pendingIntent);

        }*/

        // for(int i=0;i<7;i ++) {
            //  alarmManager.set(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis() + 1000 * 60 * 60 * 24 /*AlarmManager.INTERVAL_DAY*/, pendingIntent);
             alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pendingIntent);

            Log.d("Alarm", "Alarms set for everyday 8 am.");

        //  }
    }   
}

Broadcast Receiver

public class AlarmReciever extends BroadcastReceiver {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    int count=0;
    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    int RequestCode =777;
    @Override
    public void onReceive(Context context, Intent intent) {
          // String rec = intent.getDataString();
       // Log.d("Alarm",rec);


        Intent service1 = new Intent(context, NotificationService.class);
       // service1.setData((Uri.parse("custom://" + System.currentTimeMillis())));
        context.startService(service1);
           count++;
        preferences = context.getSharedPreferences("MyCount", Context.MODE_PRIVATE);
        editor=preferences.edit();
        editor.putInt("COUNT", count);
        editor.commit();
          incrementSum(context);

    }

 public void  incrementSum(Context context){

    int cou = preferences.getInt("COUNT",0);
    //  System.out.println(cou);
    // int c=0;
    //  int cou = preferences.getInt("COUNT",0);
    int co = preferences.getInt("C",0);
    if(cou==1){
        cou=co+1;
        editor = preferences.edit();
        editor.putInt("C",cou);
        editor.commit();
    }

    int c = preferences.getInt("C",0);
    // System.out.println("count"+cou);
    // int count = preferences.getInt("COUNT",0);
    // System.out.println("last"+count);
    System.out.println("sum" + c);
    if(c>=7) {

        Intent alarmIntent = new Intent(context, AlarmReciever.class);
        pendingIntent = PendingIntent.getBroadcast(context, RequestCode, alarmIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager!= null) {
            alarmManager.cancel(pendingIntent);
        }
        // alarmManager.cancel(pendingIntent);
    }
    // AlarmManager   alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}

Notification service

public class NotificationService extends IntentService {

    private NotificationManager notificationManager;
    private PendingIntent pendingIntent;
    private static int NOTIFICATION_ID = 1;
    Notification notification;


    public NotificationService() {
        super("testing.amaze.com.mytest");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Context context = this.getApplicationContext();
        notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent mIntent = new Intent(this, ActivityTwo.class);
        Bundle bundle = new Bundle();
        bundle.putString("test", "test");
        mIntent.putExtras(bundle);
        pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Resources res = this.getResources();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        //   Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        notification = new NotificationCompat.Builder(this)
                .setContentIntent(pendingIntent)
                //.setSmallIcon(R.drawable.ic_launcher)
                //.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                .setTicker("ticker value")
                .setAutoCancel(true)
                .setPriority(8)
              //  .setSound(soundUri)
                .setContentTitle("Notif title")
                .setContentText("Text").build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
        notification.ledARGB = 0xFFFFA500;
        notification.ledOnMS = 800;
        notification.ledOffMS = 1000;
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);
        Log.i("notif", "Notifications sent.");

    }
Waqas Raja
  • 10,802
  • 4
  • 33
  • 38
Latha
  • 125
  • 1
  • 2
  • 10
  • 1
    Please share your code. – bwegs Mar 25 '16 at 12:44
  • you can store a "variable of long type in Shared Preference, which will store System.currentTimeInmillis + 7 days in millis" , when the alarm tries to trigger after that time just cancel the alarm. – kishorepatel Mar 25 '16 at 12:49
  • read this for cancelling alarm http://stackoverflow.com/questions/14485368/delete-alarm-from-alarmmanager-using-cancel-android and this http://stackoverflow.com/questions/3330522/how-to-cancel-this-repeating-alarm – kishorepatel Mar 25 '16 at 12:49
  • i need every day notification, that notification for seven days? not after 7th day – Latha Mar 25 '16 at 13:00

2 Answers2

0

For set Alarm

public void setAlarm(Context context,int alarm_id) {
        int u_id = alarm_id;

        Intent intent1 = new Intent(context, AlarmBrodcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, u_id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context
                .getSystemService(context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, timetoSet,
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }

for Cancel Alarm

public void cancelAarm(Context context,int alarm_id) {
        int u_id = alarm_id;
        Intent intent1 = new Intent(context, AlarmBrodcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, u_id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context
                .getSystemService(context.ALARM_SERVICE);
        am.cancel(pendingIntent);
    }
Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39
0

To cancel the alarm you previously scheduled you need to use Same PendingIntent. to simplify this create a method to get the PendingIntent with some request code. like

private PendingIntent getPendingIntent(int requestCode) {
    Intent intent = new Intent(context,YourAlarmssReceiver.class);
    return PendingIntent.getBroadcast(context, requestCode,intent,0);
}

and use

((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(getPendingIntent(yourRequestCode));

keep your request code in share preferences to get it after 7 days.

EDIT :

in your BroadcastReciever , after starting NotificationService just call incrementSum method.

    public void  incrementSum(Context context){

      int cou = preferences.getInt("COUNT",0);
        cou++;
        editor = preferences.edit();
        editor.putInt("COUNT",cou);
        editor.commit();

    if(COUNT>=7) {

        Intent alarmIntent = new Intent(context, AlarmReciever.class);
        pendingIntent = PendingIntent.getBroadcast(context, RequestCode, alarmIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager!= null) {
            alarmManager.cancel(pendingIntent);
        }
        // alarmManager.cancel(pendingIntent);
    }
  }
shobhan
  • 1,460
  • 2
  • 14
  • 28
  • sorry, i did not understand ..where i need to create pending intent method and i already set request code in pending intent and why i have save request code in shared preference? – Latha Mar 25 '16 at 13:50
  • sorry.. that edited one also not working. still i'm getting notification after 7 days also.@shobhan – Latha Mar 26 '16 at 05:44
  • why i am not getting notification ,if my applications close.? i need notification if application closes also – Latha Mar 26 '16 at 10:56
  • have you removed the code in AlarmReceiver , apart from starting service and calling "incrementSum"? – shobhan Mar 26 '16 at 12:11