परिचय
Android 7.0 (API 24) से, `NotificationCompat.InboxStyle` और नोटिफिकेशन चैनल का उपयोग करके एक ही ऐप के कई नोटिफिकेशन को एक समूह में समूहित किया जा सकता है, जैसा व्हाट्सएप करता है।
कार्यान्वयन
चरण 1: लेआउट (activity_main.xml)
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Create notification"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />चरण 2: MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnCreateNotification);
btn.setOnClickListener(v -> {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setStyle(new NotificationCompat.InboxStyle())
.setContentText("Hello! This is my first push notification");
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
manager.createNotificationChannel(channel);
}
manager.notify((int) System.currentTimeMillis(), builder.build());
});
}
}चरण 3: AndroidManifest.xml
मानक मैनिफेस्ट, कोई विशेष अनुमति नहीं (Android 13+ के लिए `POST_NOTIFICATIONS` आवश्यक हो सकता है)।
व्याख्या
- `InboxStyle` एक्सपैंडेड व्यू में कई पंक्तियां दिखाता है।
- `setGroup()` और `setGroupSummary()` का उपयोग करके उन्नत ग्रुपिंग की जा सकती है।
- प्रत्येक नोटिफिकेशन के लिए एक ही चैनल ID और ग्रुप कुंजी का उपयोग करें।
यह बुनियादी उदाहरण एक नोटिफिकेशन बनाता है; वास्तविक ग्रुपिंग के लिए कई नोटिफिकेशन एक ही ग्रुप कुंजी के साथ भेजें।