2016-08-05 55 views
1

嗨,我想通知行为如下:更新现有通知的方式?

当没有从我的应用程序的单个通知,那么应该有一个创建,但是当托盘中已经有一个通知,我想更新通知的数据。

我可以得到最新的通知或其他任何方式吗?

此外,我有一个单一类型的UI +数据通知,经常发生特定事件时触发。

例如在应用程序每5分钟收到一次关于比赛得分的消息的情况下,应该根据收到的最后一条消息更新当前通知,不应该有每条比分更新消息的通知。

我的代码如下:

Intent intent = new Intent(this, MainActivity.class); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
     Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     intent.putExtra(Constants.SOME_DATA, someData); 

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
     PendingIntent.FLAG_UPDATE_CURRENT); 

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
     .setSmallIcon(R.drawable.icon) 
     .setContentTitle(title) 
     .setContentText(messageBody) 
     .setAutoCancel(true) 
     .setSound(defaultSoundUri) 
     .setContentIntent(pendingIntent); 

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

notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 

回答

0

如果你想permanetly运行单个通知和更新通知,比你有使用startForeground(NOTIFICATION_ID, notification); 创造前景通知和比你可以通过使用相同的NOTIFICATION_ID更新通知你的情况是0/*通知ID * /或者如果你想要简单的通知,而不是更新你的通知NOTIFICATION_ID并保持FLAG_UPDATE_CURRENT在你的未决意图

0

设置标志.setOngoing(true),并始终使用相同的notification id.在这种情况下是0.它会更新您当前的通知。

试试这个演示

public class MainActivity extends Activity { 

    private ImageView ImageButton; 
    int value; 

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

     ImageButton = (ImageView) findViewById(R.id.imageButton); 
     ImageButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       value++; 
       UpdateNow(value + ""); 
      } 
     }); 
    } 

    void UpdateNow(String msg) { 
     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("asd") 
       .setContentText(msg) 
       .setSound(defaultSoundUri) 
       .setOngoing(true) 
       .setContentIntent(null); 

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

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
} 
+0

@Harsh沙阿如果有一些问题在这里评论。 –

+0

@Shhali Zahid感谢您的回复,并对我迟到的回复感到抱歉。我尝试了你的建议,但仍然产生新的通知。注意:它关闭时会生成新通知,否则会更新通知。 –

+0

@HarshShah你是什么意思,当“关闭”? –