यह गाइड **लोकल नोटिफिकेशन** (डिवाइस पर उत्पन्न, सर्वर की आवश्यकता नहीं) बनाने के लिए आधुनिक, पूर्ण कार्यान्वयन प्रदान करता है। इसमें नोटिफिकेशन चैनल, अनुमतियाँ, एक्शन बटन और सर्वोत्तम अभ्यास शामिल हैं।
लोकल बनाम पुश नोटिफिकेशन
| विशेषता | लोकल नोटिफिकेशन | पुश नोटिफिकेशन (FCM) |
|---|---|---|
| स्रोत | डिवाइस पर उत्पन्न | सर्वर से भेजा गया |
| इंटरनेट आवश्यक | नहीं | हाँ |
| शेड्यूलिंग | WorkManager, AlarmManager | सर्वर-नियंत्रित |
| उपयोग का मामला | रिमाइंडर, अलार्म, ऑफलाइन अलर्ट | चैट, ब्रेकिंग न्यूज़, लाइव अपडेट |
चरण 1: निर्भरताएँ (build.gradle)
dependencies {
// कोर नोटिफिकेशन
implementation "androidx.core:core-ktx:1.12.0"
implementation "androidx.appcompat:appcompat:1.6.1"
// शेड्यूलिंग के लिए (वैकल्पिक)
implementation "androidx.work:work-runtime-ktx:2.9.0"
}
चरण 2: लेआउट (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnSimpleNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="सरल नोटिफिकेशन"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnActionNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="एक्शन बटन के साथ नोटिफिकेशन"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/btnSimpleNotification"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnScheduledNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="शेड्यूल्ड नोटिफिकेशन (10 सेकंड)"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/btnActionNotification"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
चरण 3: NotificationHelper.java - पुन: प्रयोज्य नोटिफिकेशन यूटिलिटी
package com.example.localnotification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class NotificationHelper {
public static final String CHANNEL_ID = "local_notifications";
public static final String CHANNEL_NAME = "लोकल नोटिफिकेशन";
public static final String CHANNEL_DESC = "ऐप द्वारा उत्पन्न लोकल नोटिफिकेशन";
private final Context context;
private final NotificationManagerCompat manager;
public NotificationHelper(Context context) {
this.context = context;
this.manager = NotificationManagerCompat.from(context);
createChannel();
}
private void createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
channel.enableLights(true);
channel.enableVibration(true);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
/** सरल नोटिफिकेशन दिखाएँ */
public void showSimpleNotification(String title, String message) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
manager.notify((int) System.currentTimeMillis(), builder.build());
}
/** एक्शन बटन के साथ नोटिफिकेशन दिखाएँ */
public void showNotificationWithActions(String title, String message, int notificationId) {
// मुख्य सामग्री इंटेंट
Intent contentIntent = new Intent(context, MainActivity.class);
contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentPendingIntent = PendingIntent.getActivity(
context, 0, contentIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
// एक्शन 1: उत्तर दें (BroadcastReceiver का उपयोग करता है)
Intent replyIntent = new Intent(context, NotificationActionReceiver.class);
replyIntent.setAction(NotificationActionReceiver.ACTION_REPLY);
replyIntent.putExtra(NotificationActionReceiver.EXTRA_NOTIFICATION_ID, notificationId);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(
context, 1, replyIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
// एक्शन 2: खारिज करें
Intent dismissIntent = new Intent(context, NotificationActionReceiver.class);
dismissIntent.setAction(NotificationActionReceiver.ACTION_DISMISS);
dismissIntent.putExtra(NotificationActionReceiver.EXTRA_NOTIFICATION_ID, notificationId);
PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
context, 2, dismissIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(contentPendingIntent)
.addAction(R.drawable.ic_reply, "उत्तर दें", replyPendingIntent)
.addAction(R.drawable.ic_close, "खारिज करें", dismissPendingIntent)
.setAutoCancel(true);
manager.notify(notificationId, builder.build());
}
/** विलंबित नोटिफिकेशन शेड्यूल करें (WorkManager का उपयोग करता है) */
public void scheduleNotification(String title, String message, long delayMillis) {
// कार्यान्वयन के लिए NotificationSchedulerWorker देखें
}
/** नोटिफिकेशन कैंसिल करें */
public void cancelNotification(int notificationId) {
manager.cancel(notificationId);
}
/** सभी नोटिफिकेशन कैंसिल करें */
public void cancelAllNotifications() {
manager.cancelAll();
}
}
चरण 4: एक्शन के लिए BroadcastReceiver
package com.example.localnotification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationActionReceiver extends BroadcastReceiver {
public static final String ACTION_REPLY = "com.example.ACTION_REPLY";
public static final String ACTION_DISMISS = "com.example.ACTION_DISMISS";
public static final String EXTRA_NOTIFICATION_ID = "notification_id";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);
// पैनल बंद करें
Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeDialogs);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (ACTION_DISMISS.equals(action)) {
if (notificationId != -1) manager.cancel(notificationId);
} else if (ACTION_REPLY.equals(action)) {
if (notificationId != -1) manager.cancel(notificationId);
// यहां उत्तर लॉजिक संभालें (उदाहरण के लिए, ऐप खोलें, डेटा सहेजें)
}
}
}
चरण 5: MainActivity.java
package com.example.localnotification;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private NotificationHelper notificationHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationHelper = new NotificationHelper(this);
requestNotificationPermission();
Button btnSimple = findViewById(R.id.btnSimpleNotification);
Button btnActions = findViewById(R.id.btnActionNotification);
Button btnScheduled = findViewById(R.id.btnScheduledNotification);
btnSimple.setOnClickListener(v ->
notificationHelper.showSimpleNotification("सरल नोटिफिकेशन", "यह एक बुनियादी लोकल नोटिफिकेशन है"));
btnActions.setOnClickListener(v -> {
int id = (int) System.currentTimeMillis();
notificationHelper.showNotificationWithActions(
"एक्शन के साथ नोटिफिकेशन", "बटन दबाकर इंटरैक्ट करें", id);
});
btnScheduled.setOnClickListener(v -> {
Toast.makeText(this, "10 सेकंड में नोटिफिकेशन शेड्यूल किया गया", Toast.LENGTH_SHORT).show();
scheduleDelayedNotification(10_000);
});
}
private void requestNotificationPermission() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1001);
}
}
}
// सरल हैंडलर-आधारित शेड्यूलिंग (कम अवधि के लिए ठीक)
private void scheduleDelayedNotification(long delayMillis) {
new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
notificationHelper.showSimpleNotification(
"शेड्यूल्ड नोटिफिकेशन", "यह " + (delayMillis/1000) + " सेकंड बाद दिखाई दिया!");
}, delayMillis);
}
}
चरण 6: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.localnotification">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.LocalNotification">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".NotificationActionReceiver"
android:exported="false">
</receiver>
</application>
</manifest>
चरण 7: शेड्यूल्ड नोटिफिकेशन के लिए WorkManager (वैकल्पिक, मजबूत)
// NotificationSchedulerWorker.java
public class NotificationSchedulerWorker extends Worker {
public NotificationSchedulerWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
String title = getInputData().getString("title");
String message = getInputData().getString("message");
new NotificationHelper(getApplicationContext())
.showSimpleNotification(title != null ? title : "शेड्यूल्ड",
message != null ? message : "समय हो गया!");
return Result.success();
}
}
// शेड्यूल करने के लिए:
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(NotificationSchedulerWorker.class)
.setInitialDelay(10, TimeUnit.SECONDS)
.setInputData(new Data.Builder()
.putString("title", "योजनाबद्ध")
.putString("message", "WorkManager के माध्यम से डिलीवर किया गया")
.build())
.build();
WorkManager.getInstance(context).enqueue(work);
सर्वोत्तम अभ्यास चेकलिस्ट
- [ ] **नोटिफिकेशन चैनल** बनाएँ (Android 8.0+ के लिए अनिवार्य)
- [ ] **POST_NOTIFICATIONS अनुमति** रनटाइम पर अनुरोध करें (Android 13+)
- [ ] **PendingIntent.FLAG_IMMUTABLE** उपयोग करें (Android 12+)
- [ ] **FLAG_UPDATE_CURRENT** ताज़ा डेटा के लिए
- [ ] **launchMode="singleTop"** मैनिफेस्ट में डुप्लिकेट रोकने के लिए
- [ ] **अद्वितीय notificationId** उपयोग करें (timestamp आधारित)
- [ ] **setAutoCancel(true)** मानक व्यवहार के लिए
- [ ] **WorkManager** विश्वसनीय शेड्यूलिंग के लिए (हैंडलर के बजाय)
- [ ] **NotificationManagerCompat** क्रॉस-वर्जन संगतता के लिए
उन्नत सुविधाएँ
- बिग टेक्स्ट शैली: `.setStyle(new NotificationCompat.BigTextStyle().bigText(longText))`
- चित्र शैली: `.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap))`
- इनलाइन उत्तर: `RemoteInput` के साथ `addAction()`
- प्रगति बार: `.setProgress(max, progress, false)`
- मीडिया नियंत्रण: `MediaStyle` के साथ फोरग्राउंड सर्विस