Search code examples
javaandroidandroid-notificationsandroid-notification-bar

How can i open Activity when notification click


I need use notification with click event, i have notification method but this method don't open my activity.

My code:

 private void sendNotification(String msg) {

        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
        .setContentTitle("EXX")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg)          
        .setOngoing(true);          
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}    

is this possible,

thanks.


Solution

  • Yes, it is possible.

    Change Your method, like that;

    private void sendNotification(String msg) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("yourpackage.notifyId", NOTIFICATION_ID);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder mBuilder =  new NotificationCompat.Builder(this)
                .setContentTitle("EXX")
                .setSmallIcon(R.drawable.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle()
                .bigText(msg))
                .addAction(getNotificationIcon(), "Action Button", pIntent)
                .setContentIntent(pIntent)
                .setContentText(msg)
                .setOngoing(true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    

    and add your mainactivity

        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    

    this code working.