Advertisement
BenTibnam

Basic Notification with Load Intent in Android

Dec 14th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.36 KB | None | 0 0
  1. package com.compgensoft.notificationtutorial;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4. import androidx.core.app.NotificationCompat;
  5. import androidx.core.app.NotificationManagerCompat;
  6.  
  7. import android.app.NotificationChannel;
  8. import android.app.NotificationManager;
  9. import android.app.PendingIntent;
  10. import android.content.Intent;
  11. import android.os.Build;
  12. import android.os.Bundle;
  13.  
  14. public class MainActivity extends AppCompatActivity {
  15.     public static final String CHANNEL_ID = "channel";
  16.  
  17.  
  18.     @Override
  19.     protected void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.activity_main);
  22.  
  23.         // creating the channel
  24.         if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
  25.             String name = CHANNEL_ID;
  26.             String description = "This is the channel description";
  27.             int importance = NotificationManager.IMPORTANCE_DEFAULT;
  28.             NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
  29.             channel.setDescription(description);
  30.             NotificationManager notificationManager = getSystemService(NotificationManager.class);
  31.             notificationManager.createNotificationChannel(channel);
  32.         }
  33.  
  34.         // setting on tap notification
  35.         Intent intent = new Intent(this, AlertDetails.class);
  36.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  37.         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
  38.  
  39.         // building the notification
  40.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
  41.                 .setSmallIcon(R.drawable.call)
  42.                 .setContentTitle("Channel")
  43.                 .setContentText("I am a notification!")
  44.                 // to set longer style do .setStyle(new NotificationCompat.BigTextStyle().bigText("much longer text that can't fit on one line"))
  45.                 .setPriority(NotificationCompat.PRIORITY_DEFAULT)
  46.                 .setContentIntent(pendingIntent)
  47.                 .setAutoCancel(true);
  48.  
  49.         // showing the notification
  50.         NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
  51.  
  52.         int notificationId = 1;
  53.         notificationManagerCompat.notify(notificationId, builder.build());
  54.  
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement