While trying to update and add features to my old open source Hourglass app, I decided that the issue posted asking for a notification cancel button was a pretty good idea!

Screenshot from 2018-05-02 13-12-03

Now you can cancel your timer at any time from the notification bar! The code was pretty simple, actually, and you can read the entire commit on my GitLab, but here is the important part:

// as a result of notification action
Intent detailsIntent = new Intent(MainActivity.this, CancelActivity.class);
detailsIntent.putExtra("EXTRA_DETAILS_ID", 42);
PendingIntent detailsPendingIntent = PendingIntent.getActivity(
      MainActivity.this,
      0,
      detailsIntent,
      PendingIntent.FLAG_UPDATE_CURRENT
      );

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.hourglass).setWhen(System.currentTimeMillis()+recureTime).setUsesChronometer(true)
        .setContentTitle("Hourglass").setContentText(intentPhrase).addAction(
                android.R.drawable.ic_notification_clear_all, "Cancel", detailsPendingIntent);

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(context, 0 , intent, PendingIntent.FLAG_UPDATE_CURRENT);

This mumbo jumbo just allows the cancel button to be displayed, which, if pressed, calls the CancelActivity class.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set the screen orientation to portrait to keep the screen rotation bug from stoping
    // the timer on some phones.
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Just log.
    Log.i("WJH", "CancellAll.");
    allCancel = true;
    finish();

}

The moment the CancelActivity.java class opens, it set’s the boolean allCancel to true (meaning yes, we want to cancel) and exits back to the MainActivity class, where the timer is running.

Then, on every tick of the timer, it checks to see if allCancel is true or false. If true, it cancels the timer, repeating timer, and recurring alarm. If false, it continues to count down as usual. Praise God! It actually works! Be sure to check out revision 1.9 of the app for this latest feature! And thanks to “brunetton” for the great idea!

Linux – keep it simple.

Leave a Reply

Your email address will not be published. Required fields are marked *