-1

I created a button that push a notification, but I want this notification to appear after 10 second. How to do that? This is my MainActivity

import android.app.Notification;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private NotificationManagerCompat notificationManager;
    private EditText editTextTitle;
    private EditText editTextMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        notificationManager= NotificationManagerCompat.from(this);
        editTextTitle = findViewById(R.id.editTxtTitle);
        editTextMessage = findViewById(R.id.editTxtMessage);
    }
    public void sendOnChannel(View view){
        String title = editTextTitle.getText().toString();
        String message = editTextMessage.getText().toString();
        Notification notification = new NotificationCompat.Builder(this,CHANNEL_1_ID)
                .setSmallIcon(R.drawable.ic_one).setContentTitle(title).setContentText(message)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE).build();
        notificationManager.notify(1, notification);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Imatabil
  • 19
  • 1
  • 5
  • I think you need a delay, try cheching this, for example: https://stackoverflow.com/questions/42379301/how-to-use-postdelayed-correctly-in-android-studio – Luca Murra Sep 10 '21 at 16:16

1 Answers1

0

You can achieve this with the postDelayed method of all View items:

public void sendOnChannel(View view){
    String title = editTextTitle.getText().toString();
    String message = editTextMessage.getText().toString();
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
            .setSmallIcon(R.drawable.ic_one).setContentTitle(title).setContentText(message)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE).build();
    
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            notificationManager.notify(1, notification);
        }
    }, 10 * 1000);
}
Luca Murra
  • 1,848
  • 14
  • 24