Ouvrez l'application après avoir cliqué sur Notification

116

J'ai une notification dans mon application avec le code suivant:

//Notification Start

   notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

   int icon = R.drawable.n1; 
   CharSequence tickerText = "Call Blocker";
   long when = System.currentTimeMillis(); //now
   Notification notification = new Notification(icon, tickerText, when);
   Intent notificationIntent = new Intent(context, Main.class);
   PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

   Context context = getApplicationContext();
   CharSequence title = "Call Blocker";
   text = "Calls will be blocked while driving";

   notification.setLatestEventInfo(context, title, text, contentIntent);

   notification.flags |= Notification.FLAG_ONGOING_EVENT;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notificationManager.notify(1, notification);

}

Mes notifications se déclenchent très bien, mais mon problème est que, lorsque je clique sur la notification dans le centre de notifications, cela ne démarre pas mon application.

En gros, après avoir cliqué sur ma notification, rien ne se passe! Que dois-je faire pour démarrer mon activité principale après avoir cliqué sur ma notification. Merci.

Reza_Rg
la source
2
essayez ceci
Ram kiran
2
bougez Context context = getApplicationContext();avant Notification notification = new Notification(icon, tickerText, when);peut-être que vous ne passez pas le bon contexte pour commencer l'activité
ρяσѕρєя K
Il y a plus de 4 ans ... quel long voyage tu fais depuis ce jour :) mais rien ne change dans la notification Android;)
Hamed Ghadirian
@HamedGh Il y a presque 5 ans! :)))
Reza_Rg
1
@Reza_Rg a 7 ans. J'ai le même problème!
fuliozor

Réponses:

156

Voir le code ci-dessous. J'utilise ça et ça ouvre mon HomeActivity.

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
Nirali
la source
1
Il me manquait le FLAG_AUTO_CANCEL. Merci!
JonasVautherin
10
La notification (int, java.lang.CharSequence, long) est obsolète depuis ce post, il faut utiliser NotificationCompat.Builder.
Bourne
8
ne peut pas résoudre la méthodenotification.setLatestEventInfo
Ravi Vaniya
61

Voici un exemple d'utilisation de la classe NotificationCompact.Builder qui est la version récente pour générer la notification.

private void startNotification() {
    Log.i("NextActivity", "startNotification");

 // Sets an ID for the notification
      int mNotificationId = 001;

    // Build Notification , setOngoing keeps the notification always in status bar
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ldb)
                    .setContentTitle("Stop LDB")
                    .setContentText("Click to stop LDB")
                    .setOngoing(true);

    // Create pending intent, mention the Activity which needs to be 
    //triggered when user clicks on notification(StopScript.class in this case)

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);


    mBuilder.setContentIntent(contentIntent);


    // Gets an instance of the NotificationManager service
   NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotificationManager.notify(mNotificationId, mBuilder.build());


}
Vins
la source
Qu'est-ce que je fais mal? J'ai exactement ce code mais cela ne fonctionne pas lorsque je clique sur la notification.
TheRealChx101
15

On dirait que vous avez manqué cette partie,

notification.contentIntent = pendingIntent;

Essayez d'ajouter ceci et cela devrait fonctionner.

Andro Selva
la source
15

Veuillez utiliser le code ci-dessous pour un exemple complet de notification simple, dans ce code, vous pouvez ouvrir l'application après avoir cliqué sur Notification, cela résoudra votre problème.

public class AndroidNotifications extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button notificationButton = (Button) findViewById(R.id.notificationButton);

        notificationButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // Notification Title and Message
                        Notification("Dipak Keshariya (Android Developer)",
                                "This is Message from Dipak Keshariya (Android Developer)");
                    }
                }, 0);
            }
        });
    }

    // Notification Function
    private void Notification(String notificationTitle,
            String notificationMessage) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        android.app.Notification notification = new android.app.Notification(
                R.drawable.ic_launcher, "Message from Dipak Keshariya! (Android Developer)",
                System.currentTimeMillis());

        Intent notificationIntent = new Intent(this, AndroidNotifications.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        notification.setLatestEventInfo(AndroidNotifications.this,
                notificationTitle, notificationMessage, pendingIntent);
        notificationManager.notify(10001, notification);
    }
}

Et voir le lien ci-dessous pour plus d'informations.

Exemple de notification simple

Dipak Keshariya
la source
6

Utilisez le code ci-dessous pour créer une notification pour une activité ouverte. Ça marche pour moi. Pour le code complet

 Intent myIntent = new Intent(context, DoSomething.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(
        context, 
        0, 
        myIntent, 
        Intent.FLAG_ACTIVITY_NEW_TASK);

 myNotification = new NotificationCompat.Builder(context)
   .setContentTitle("Exercise of Notification!")
   .setContentText("Do Something...")
   .setTicker("Notification!")
   .setWhen(System.currentTimeMillis())
   .setContentIntent(pendingIntent)
   .setDefaults(Notification.DEFAULT_SOUND)
   .setAutoCancel(true)
   .setSmallIcon(R.drawable.ic_launcher)
   .build();

 notificationManager = 
   (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
 notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
Ankit Kumar Garg
la source
C'est setAutoCancel(true)ce que je cherchais.
Wojtek
5

utilisez ceci:

    Notification mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_music)
                    .setContentTitle(songName).build();


    mBuilder.contentIntent=  PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

contentIntent se chargera de l'activité d'ouverture lorsque la notification cliquera

Lily Sedghi
la source
4
public void addNotification()
{
    NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this);
    mBuilder.setSmallIcon(R.drawable.email);
    mBuilder.setContentTitle("Notification Alert, Click Me!");
    mBuilder.setContentText("Hi,This notification for you let me check");
    Intent notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent conPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(conPendingIntent);

    NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0,mBuilder.build());
    Toast.makeText(MainActivity.this, "Notification", Toast.LENGTH_SHORT).show();

}
Cheikh Mohib
la source
1
Bien que cet extrait de code puisse résoudre la question, inclure une explication aide vraiment à améliorer la qualité de votre message. N'oubliez pas que vous répondez à la question aux lecteurs à l'avenir, et que ces personnes pourraient ne pas connaître les raisons de votre suggestion de code.
Alessio
3

Grâce aux messages ci-dessus, voici les lignes principales - distillées à partir des réponses de code plus longues - qui sont nécessaires pour connecter une notification avec un écouteur de clic défini pour ouvrir une activité d'application.

private Notification getNotification(String messageText) {

    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentText(messageText);
    // ...

    Intent appActivityIntent = new Intent(this, SomeAppActivity.class);

    PendingIntent contentAppActivityIntent =
            PendingIntent.getActivity(
                            this,  // calling from Activity
                            0,
                            appActivityIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(contentAppActivityIntent);

    return builder.build();
}
Gene Bo
la source
2
public static void notifyUser(Activity activity, String header,
        String message) {
    NotificationManager notificationManager = (NotificationManager) activity
            .getSystemService(Activity.NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent(
            activity.getApplicationContext(), YourActivityToLaunch.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
    stackBuilder.addParentStack(YourActivityToLaunch.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent pIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(activity)
            .setContentTitle(header)
            .setContentText(message)
            .setDefaults(
                    Notification.DEFAULT_SOUND
                            | Notification.DEFAULT_VIBRATE)
            .setContentIntent(pIntent).setAutoCancel(true)
            .setSmallIcon(drawable.notification_icon).build();
    notificationManager.notify(2, notification);
}
Néo
la source
1

Prends mon exemple ...

 public void createNotification() {
        NotificationManager notificationManager = (NotificationManager) 
              getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.icon,
            "message", System.currentTimeMillis());
        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = { 0, 100, 600, 100, 700};
        vibrator.vibrate(pattern, -1);
     Intent intent = new Intent(this, Main.class);
     PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
     String sms = getSharedPreferences("SMSPREF", MODE_PRIVATE).getString("incoming", "EMPTY");
        notification.setLatestEventInfo(this, "message" ,
            sms, activity);
        notification.number += 1;
        notificationManager.notify(0, notification);

      }
Timonvlad
la source
1

C'est la façon dont j'ai abordé.

public class AppFCMService extends FirebaseMessagingService {

    private final static String TAG = "FCM Message";
    String notify, requstId, Notification;
    PendingIntent pendingIntent;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        //split string and getting order id from notification
        String Str = remoteMessage.getNotification().getBody();
        String[] tmp;
        tmp = Str.split(" ");
        String temp1 = tmp[0];
        String temp2 = tmp[1];
        String id = tmp[2];
        notify = temp1 + " " + temp2;
        requstId = id;
        showNotification(remoteMessage.getNotification().getBody());
    }

    private void showNotification(String messageBody) {
        // check whether session has been initiated or not
        if (new SessionHelper(getApplicationContext()).isLoggedIn()) {

            if (notify.equalsIgnoreCase("Travel request")) {

                Intent intent = new Intent(this, ViewTravelDetailsActivity.class);
                intent.putExtra("TravelRequestID", requstId);
                intent.putExtra("BackPress", "Notify");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);

            } else if (notify.equalsIgnoreCase("Timesheet replied")) {

                Intent intent = new Intent(this, ViewReplyActivity.class);
                intent.putExtra("timesheetActivityID", requstId);
                intent.putExtra("BackPress", "Notify");
                intent.putExtra("RealmData", "DeleteRealm");
                intent.putExtra("isToday", "true");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            } else {

                Intent intent = new Intent(this, Dashboard.class);
                intent.putExtra("timesheetActivityID", requstId);
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            }
        } else {

            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("timesheetActivityID", requstId);
            pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        Bitmap notifyImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(notifyImage)
                .setColor(Color.parseColor("#FFE74C3C"))
                .setContentTitle("TEST")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}
arc_shiva
la source