Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Android

एंड्रॉइड नोटिफिकेशन में बटन कैसे जोड़ें?

यह गाइड **NotificationCompat.Action** और **BroadcastReceiver** का उपयोग करके एंड्रॉइड नोटिफिकेशन में इंटरैक्टिव एक्शन बटन (जैसे "उत्तर दें", "स्नूज़", "खारिज करें") जोड़ने का तरीका दिखाता है।

मुख्य अवधारणा

नोटिफिकेशन एक्शन बटन के लिए PendingIntent.getBroadcast() की आवश्यकता होती है (getActivity() नहीं) ताकि वे ऐप UI लॉन्च किए बिना पृष्ठभूमि में चल सकें। प्रत्येक बटन एक BroadcastReceiver को ट्रिगर करता है जो कार्रवाई को संभालता है।

चरण 1: BroadcastReceiver - बटन हैंडलर

package com.example.notificationbuttons;

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_SNOOZE = "com.example.ACTION_SNOOZE";
    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);

        // 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_SNOOZE.equals(action)) {
            // स्नूज़: नोटिफिकेशन हटाएँ, बाद के लिए पुनः शेड्यूल करें
            if (notificationId != -1) manager.cancel(notificationId);
            scheduleSnooze(context, 10 * 60 * 1000); // 10 मिनट
            
        } else if (ACTION_REPLY.equals(action)) {
            // उत्तर दें: RemoteInput से टेक्स्ट प्राप्त करें (यदि उपयोग कर रहे हैं)
            // नोटिफिकेशन हटाएँ, उत्तर संभालें
            if (notificationId != -1) manager.cancel(notificationId);
            handleReply(context, intent);
        }
    }

    private void scheduleSnooze(Context context, long delayMillis) {
        // WorkManager या AlarmManager का उपयोग करके पुनः शेड्यूल करें
        // सरल डेमो के लिए तत्काल पुनः दिखा रहे हैं
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            // यहां नोटिफिकेशन पुनः दिखाएँ
        }, delayMillis);
    }

    private void handleReply(Context context, Intent intent) {
        // RemoteInput के साथ इनलाइन उत्तर के लिए:
        // Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
        // if (remoteInput != null) { String reply = remoteInput.getCharSequence("reply_key").toString(); }
        
        // सरल डेमो: मुख्य ऐप खोलें
        Intent mainIntent = new Intent(context, MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mainIntent.putExtra("reply_handled", true);
        context.startActivity(mainIntent);
    }
}

चरण 2: MainActivity.java - बटन के साथ नोटिफिकेशन बनाएँ

package com.example.notificationbuttons;

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 android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static final String CHANNEL_ID = "action_buttons_channel";
    private static final String CHANNEL_NAME = "एक्शन बटन नोटिफिकेशन";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createNotificationChannel();

        Button btn = findViewById(R.id.btnCreateNotification);
        btn.setOnClickListener(v -> createNotificationWithButtons());
    }

    private void createNotificationWithButtons() {
        int notificationId = (int) System.currentTimeMillis();

        // --- मुख्य सामग्री टैप (एक्टिविटी खोलता है) ---
        Intent contentIntent = new Intent(this, MainActivity.class);
        contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentPendingIntent = PendingIntent.getActivity(
            this, 0, contentIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        // --- एक्शन 1: उत्तर दें (इनलाइन RemoteInput के साथ) ---
        // RemoteInput उपयोगकर्ता को नोटिफिकेशन से सीधे टाइप करने की अनुमति देता है
        android.app.RemoteInput remoteInput = new android.app.RemoteInput.Builder("reply_key")
            .setLabel("उत्तर टाइप करें...")
            .build();

        Intent replyIntent = new Intent(this, NotificationActionReceiver.class);
        replyIntent.setAction(NotificationActionReceiver.ACTION_REPLY);
        replyIntent.putExtra(NotificationActionReceiver.EXTRA_NOTIFICATION_ID, notificationId);
        PendingIntent replyPendingIntent = PendingIntent.getBroadcast(
            this, 1, replyIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_reply, "उत्तर दें", replyPendingIntent)
            .addRemoteInput(remoteInput)
            .setAllowGeneratedReplies(true)
            .build();

        // --- एक्शन 2: स्नूज़ (सरल बटन) ---
        Intent snoozeIntent = new Intent(this, NotificationActionReceiver.class);
        snoozeIntent.setAction(NotificationActionReceiver.ACTION_SNOOZE);
        snoozeIntent.putExtra(NotificationActionReceiver.EXTRA_NOTIFICATION_ID, notificationId);
        PendingIntent snoozePendingIntent = PendingIntent.getBroadcast(
            this, 2, snoozeIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_snooze, "स्नूज़ (10 मिनट)", snoozePendingIntent)
            .build();

        // --- एक्शन 3: खारिज करें ---
        Intent dismissIntent = new Intent(this, NotificationActionReceiver.class);
        dismissIntent.setAction(NotificationActionReceiver.ACTION_DISMISS);
        dismissIntent.putExtra(NotificationActionReceiver.EXTRA_NOTIFICATION_ID, notificationId);
        PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            this, 3, dismissIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Action dismissAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_close, "खारिज करें", dismissPendingIntent)
            .build();

        // --- नोटिफिकेशन बनाएँ ---
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("इंटरैक्टिव नोटिफिकेशन")
            .setContentText("एक्शन बटन के साथ: उत्तर दें, स्नूज़, खारिज करें")
            .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("यह नोटिफिकेशन तीन एक्शन बटन दिखाता है। 'उत्तर दें' इनलाइन टेक्स्ट इनपुट खोलता है। 'स्नूज़' 10 मिनट के लिए स्थगित करता है। 'खारिज करें' हटा देता है।"))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(contentPendingIntent)
            .addAction(replyAction)
            .addAction(snoozeAction)
            .addAction(dismissAction)
            .setAutoCancel(true);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(notificationId, builder.build());
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("इंटरैक्टिव एक्शन बटन वाले नोटिफिकेशन");
            channel.enableVibration(true);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
}

चरण 3: लेआउट (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/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="एक्शन बटन के साथ नोटिफिकेशन दिखाएँ"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

चरण 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.notificationbuttons">

    <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.NotificationButtons">

        <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>

ड्रॉएबल संसाधन (res/drawable/ में जोड़ें)

निम्नलिखित XML फ़ाइलें बनाएँ या मौजूदा आइकन का उपयोग करें:

ic_reply.xml

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
    <path android:fillColor="#FFFFFF" android:pathData="M21,15H3V5H21V15ZM19,7H5V13H19V7Z"/>
</vector>

ic_snooze.xml

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
    <path android:fillColor="#FFFFFF" android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zm0,-2c3.31,0 6,-2.69 6,-6s-2.69,-6 -6,-6 -6,2.69 -6,6 2.69,6 6,6zm0,-10c1.1,0 2,.9 2,2s-.9,2 -2,2 -2,-0.9 -2,-2 .9,-2 2,-2z"/>
</vector>

ic_close.xml

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
    <path android:fillColor="#FFFFFF" android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12 19,6.41z"/>
</vector>

एक्शन बटन प्रकार

प्रकारविवरणउपयोग का मामला
सरल बटनNotificationCompat.Action.Builder(icon, title, pendingIntent)खारिज करें, स्नूज़, खोलें, साझा करें
इनलाइन उत्तर (RemoteInput).addRemoteInput() के साथ Action.Builderसंदेश उत्तर, त्वरित टिप्पणी, खोज
प्रगति/लोडिंगसेटप्रोग्रेस के साथ कस्टम लेआउटडाउनलोड, अपलोड, सिंक स्थिति

महत्वपूर्ण नोट्स

  • अद्वितीय अनुरोध कोड: प्रत्येक PendingIntent के लिए अलग (0, 1, 2, 3) टकराव से बचने के लिए
  • BroadcastReceiver exported="false": आंतरिक रिसीवर के लिए सुरक्षा सर्वोत्तम अभ्यास
  • ACTION_CLOSE_SYSTEM_DIALOGS: बटन दबाए जाने पर नोटिफिकेशन शेड बंद करता है
  • RemoteInput: Android 7.0+ (API 24) की आवश्यकता; उपयोगकर्ता को पैनल खोले बिना उत्तर देने की अनुमति देता है
  • अधिकतम एक्शन: Android 7.0 से पहले 3 तक; नए संस्करणों पर अधिक लेकिन 3 UI के लिए आदर्श

उन्नत: Wear OS के लिए क्रियाएँ

.extend(new NotificationCompat.WearableExtender()
    .addAction(replyAction)
    .addAction(snoozeAction)
    .setHintShowBackgroundOnly(false))
  1. एंड्रॉइड में डायनामिकली बटन कैसे जोड़ें? एंड्रॉइड में डायनामिकली बटन कैसे जोड़ें?

    एंड्रॉइड में रनटाइम पर प्रोग्रामेटिकली बटन (या कोई व्यू) जोड़ना कभी-कभी लेआउट XML में नहीं, बल्कि डेटा/शर्तों के आधार पर रनटाइम पर व्यूज जोड़ने पड़ते हैं। इसके लिए: **पैरेंट व्यूग्रुप प्राप्त करें → नया व्यू बनाएं → LayoutParams सेट करें → addView() कॉल करें।** चरण 1: नया प्रोजेक्ट बनाएं Android St

  1. Android में PreferenceScreen पर बटन कैसे जोड़ें? Android में PreferenceScreen पर बटन कैसे जोड़ें?

    AndroidX Preference लाइब्रेरी का उपयोग करके सेटिंग्स स्क्रीन में कस्टम एक्शन बटन जोड़ने का तरीका। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में नया प्रोजेक्ट बनाएं। चरण 2: एक्टिविटी लेआउट res/layout/activity_main.xml - Fragment कंटेनर: <LinearLayout xmlns:android=https://schemas.android.com/apk

  1. एंड्रॉइड 8 स्नूज़ मास्टर करें: बेहतर नींद के लिए नोटिफिकेशन प्रबंधित करें एंड्रॉइड 8 स्नूज़ मास्टर करें: बेहतर नींद के लिए नोटिफिकेशन प्रबंधित करें

    हम में से ज्यादातर के लिए बिस्तर पर जाने से पहले दिन का आखिरी काम आने वाले दिन के लिए अलार्म सेट करना होता है। हालांकि, हम में से ज्यादातर आरामदायक बिस्तर के दायरे से खुद को बाहर खींचने से पहले कम से कम कुछ बार स्नूज़ बटन दबाते हैं। आश्चर्यजनक रूप से, ये दो स्नूज़ के बीच के कुछ मिनट हैं जब हमें सबसे