【问题标题】:Android notification keeps launching appAndroid 通知不断启动应用程序
【发布时间】:2015-05-20 14:41:34
【问题描述】:

我正在创建一个通知,当收到通知时,应用程序就会启动。我的问题是如何阻止这种情况发生?

final private static void generateNotification(Context context, String message){
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle(context.getString(R.string.app_name))
        .setContentIntent(intent)
        .setContentText(message)
        .setAutoCancel(true) 
        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
} 

在 GCMIntentService 中调用通知:

@Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    String response = intent.getExtras().getString("response");

    switch(response){
        case "logout":
            String message = "You logged into another device!";
            //displayMessage(context, message);
            // notifies user
            generateNotification(context, message);
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        break;
        default:

        break;
    }



}

【问题讨论】:

  • "当收到应用程序时",你确定吗?不是点击时?
  • 是的,即使我没有点击应用程序启动的通知
  • 发布这段代码是从哪里调用的,因为我认为这里没有问题。
  • 你有一个服务和一个广播接收器一遍又一遍地触发吗?如果是这样,那就是问题
  • @Jasz 我没有广播接收器:S

标签: java android notifications push-notification


【解决方案1】:

请不要执行我在下面注释掉的这些行。该代码在收到的"logout" 消息上启动一个活动。

generateNotification(context, message);
//Intent i = new Intent(context, MainActivity.class);
//i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(i);

【讨论】:

  • 太棒了!这行得通,但是现在我如何在通知点击或应用程序打开时运行它?
  • 你试过点击它吗?因为你的代码似乎有这个虽然使用setContentIntent
  • 完美 :) 正是我所需要的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多