Notification Click Handling in Android Part 2
Please read Part 1 Before this so here The issue is that when you click the notification most of the user can feel, it opens the
dashboard activity but doesn't handle the certificate ID properly. Here's the complete fix:🔧 1. Update MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM_Service";
private static final String CHANNEL_ID = "approval_channel";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Handle Data Payload
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
Log.d(TAG, "Message data payload: " + data);
String title = data.get("title");
String body = data.get("body");
String certId = data.get("certId");
String certNo = data.get("certNo");
String action = data.get("action");
String senderEmpNo = data.get("senderEmpNo");
sendNotification(title, body, certId, certNo, action, senderEmpNo);
}
// Handle Notification Payload
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Log.d(TAG, "Notification Body: " + body);
// Get data from notification payload
Map<String, String> data = remoteMessage.getData();
String certId = data.get("certId");
String certNo = data.get("certNo");
String action = data.get("action");
String senderEmpNo = data.get("senderEmpNo");
sendNotification(title, body, certId, certNo, action, senderEmpNo);
}
}
@Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.d(TAG, "FCM token refreshed: " + token);
// Save token locally
getSharedPreferences("FCM_PREFS", MODE_PRIVATE)
.edit()
.putString("fcm_token", token)
.apply();
// Get employee number
String empNo = getSharedPreferences("LOGIN_DATA", MODE_PRIVATE)
.getString("EMP_NO", "");
if (empNo != null && !empNo.trim().isEmpty()) {
FcmTokenManager.saveTokenToServer(getApplicationContext(), empNo, token);
}
}
private void sendNotification(String title, String body, String certId,
String certNo, String action, String senderEmpNo) {
// ✅ FIX: Create intent with proper extras
Intent intent = new Intent(this, dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// ✅ Pass all data as extras
if (certId != null && !certId.isEmpty()) {
intent.putExtra("CERT_ID", certId);
}
if (certNo != null && !certNo.isEmpty()) {
intent.putExtra("CERT_NO", certNo);
}
if (action != null && !action.isEmpty()) {
intent.putExtra("ACTION", action);
}
if (senderEmpNo != null && !senderEmpNo.isEmpty()) {
intent.putExtra("SENDER_EMPNO", senderEmpNo);
}
// ✅ Add a flag to indicate notification click
intent.putExtra("FROM_NOTIFICATION", true);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
(int) System.currentTimeMillis(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_action_gear)
.setContentTitle(title != null ? title : "Urgency Certificate")
.setContentText(body != null ? body : "New certificate requires your approval")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Certificate Approvals",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("Notifications for certificate approvals");
channel.enableVibration(true);
channel.enableLights(true);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
}
}
🔧 2. Update Dashboard Activity where you want to show to Handle Notification Click
// In dashboard.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
// ... existing code ...
// ✅ Handle notification click
handleNotificationIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// ✅ Handle notification click when app is already open
handleNotificationIntent(intent);
}
/**
* Handle notification click intent
*/
private void handleNotificationIntent(Intent intent) {
if (intent == null) return;
// ✅ Check if this is from notification
boolean fromNotification = intent.getBooleanExtra("FROM_NOTIFICATION", false);
if (fromNotification) {
String certId = intent.getStringExtra("CERT_ID");
String certNo = intent.getStringExtra("CERT_NO");
String action = intent.getStringExtra("ACTION");
String senderEmpNo = intent.getStringExtra("SENDER_EMPNO");
Log.d("NOTIFICATION_CLICK", "Certificate ID: " + certId);
Log.d("NOTIFICATION_CLICK", "Certificate No: " + certNo);
Log.d("NOTIFICATION_CLICK", "Action: " + action);
// ✅ Show alert dialog with certificate details
showNotificationAlert(certId, certNo, action, senderEmpNo);
// ✅ Open the certificate detail
if (certId != null && !certId.isEmpty()) {
openCertificateDetail(certId, certNo);
}
}
}
/**
* Show alert dialog with notification details
*/
private void showNotificationAlert(String certId, String certNo, String action, String senderEmpNo) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("📬 Notification");
String message = "Certificate #: " + (certNo != null ? certNo : "N/A") + "\n";
message += "Certificate ID: " + (certId != null ? certId : "N/A") + "\n";
message += "Action: " + (action != null ? action : "View") + "\n";
if (senderEmpNo != null && !senderEmpNo.isEmpty()) {
message += "From: " + senderEmpNo;
}
builder.setMessage(message);
builder.setPositiveButton("Open Certificate", (dialog, which) -> {
if (certId != null && !certId.isEmpty()) {
openCertificateDetail(certId, certNo);
}
});
builder.setNegativeButton("OK", (dialog, which) -> dialog.dismiss());
builder.setCancelable(true);
builder.show();
}
/**
* Open certificate detail activity
*/
private void openCertificateDetail(String certId, String certNo) {
try {
// ✅ Get the current user's designation
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String dsg = prefs.getString("DSG", "");
// ✅ Determine which activity to open based on designation
if (dsg.equalsIgnoreCase("AWM") || dsg.equalsIgnoreCase("DYCME") ||
dsg.equalsIgnoreCase("CWE") || dsg.equalsIgnoreCase("DYCMM")) {
// Open the approval view activity
Intent intent = new Intent(this, awm_fp_request_view_for_action.class);
intent.putExtra("CERT_ID", certId);
intent.putExtra("FORWARD_TO", prefs.getString("EMPNO", ""));
startActivity(intent);
} else {
// Open the certificate detail view
Intent intent = new Intent(this, CertificateDetailActivity.class);
intent.putExtra("CERT_ID", certId);
intent.putExtra("CERT_NO", certNo);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Error opening certificate: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
🔧 3. Create CertificateDetailActivity.java (If not exists)
package nanoakhi.rcfinternal.urgency;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import nanoakhi.rcfinternal.R;
public class CertificateDetailActivity extends AppCompatActivity {
private TextView tvCertNo, tvCertId, tvStatus, tvMessage;
private RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_certificate_detail);
tvCertNo = findViewById(R.id.tvCertNo);
tvCertId = findViewById(R.id.tvCertId);
tvStatus = findViewById(R.id.tvStatus);
tvMessage = findViewById(R.id.tvMessage);
requestQueue = Volley.newRequestQueue(this);
String certId = getIntent().getStringExtra("CERT_ID");
String certNo = getIntent().getStringExtra("CERT_NO");
if (certId != null) {
tvCertId.setText("Certificate ID: " + certId);
tvCertNo.setText("Certificate No: " + (certNo != null ? certNo : "N/A"));
fetchCertificateDetails(certId);
} else {
tvMessage.setText("No certificate ID provided");
}
}
private void fetchCertificateDetails(String certId) {
String url = "/get_certificate.php?CERT_ID=" + certId;
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url,
null,
response -> {
try {
boolean success = response.getBoolean("success");
if (success) {
JSONObject data = response.getJSONObject("data");
String status = data.optString("CURRENT_STATUS", "Unknown");
String priority = data.optString("PRIORITY", "Normal");
tvStatus.setText("Status: " + status + " | Priority: " + priority);
tvMessage.setText("Certificate loaded successfully");
} else {
tvMessage.setText("Failed to load certificate details");
}
} catch (Exception e) {
e.printStackTrace();
tvMessage.setText("Error: " + e.getMessage());
}
},
error -> {
tvMessage.setText("Network error: " + error.getMessage());
}
);
requestQueue.add(request);
}
}
🔧 4. Create activity_certificate_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:background="#F5F5F5">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Certificate Details"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#1A237E"
android:gravity="center"
android:layout_marginBottom="16dp"/>
<TextView
android:id="@+id/tvCertId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Certificate ID: "
android:textSize="14sp"
android:textColor="#333333"
android:layout_marginBottom="8dp"/>
<TextView
android:id="@+id/tvCertNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Certificate No: "
android:textSize="14sp"
android:textColor="#333333"
android:layout_marginBottom="8dp"/>
<TextView
android:id="@+id/tvStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Status: "
android:textSize="14sp"
android:textColor="#333333"
android:layout_marginBottom="8dp"/>
<TextView
android:id="@+id/tvMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Loading..."
android:textSize="14sp"
android:textColor="#757575"
android:gravity="center"
android:layout_marginTop="8dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
🎯 How It Works Now
Notification Received →
MyFirebaseMessagingService.onMessageReceived()Notification Displayed → System notification with pending intent
User Clicks Notification → Opens
dashboardactivityDashboard Detects → Checks
FROM_NOTIFICATIONflagShows Alert Dialog → Displays certificate details
User Clicks "Open Certificate" → Opens the certificate detail/approval screen
Now when you click the notification, it will show an alert dialog with certificate details and then open the appropriate screen!


Post a Comment
0Comments