Question

I have this object:

public  void timerDistraction(final View view) {

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
         //Do something after time
           Toast.makeText(getApplicationContext(), 
                   "Button is clicked", Toast.LENGTH_LONG).show();

            Notification notification = new Notification.Builder(this)
              .setContentTitle("Basic Notification")
              .setContentText("This is my example of basic notification")
              .setSmallIcon(R.drawable.ic_launcher).build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            NotificationManager notificationManager = getNotificationManager();
            notificationManager.notify(0, notification);
            Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notificationSound);
            r.play();

     }
     }, 5000);

And the line

Notification notification = new Notification.Builder(this)

Has an error, presumably because of the (this)

Can anyone point me in the right direction. I've tried changing it to the function or null, but no progress. If I have just the notification code itself, without the delay, it works.

Was it helpful?

Solution

When you are in the Runnable, this became the Runnable and not the context of your Activity. Since you must pass a context as parameter, it triggers an error. To get the correct context, you can use the same way as the one you used for the Toast:

Notification notification = new Notification.Builder(getApplicationContext());

In this case, you will effectively pass your Activity context and not your Runnable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top