2014-02-26 112 views
0

我有一个应用程序使用正在进行的通知让用户知道其正在运行。这很方便,因为它需要在后台一直运行以接收消息。该应用程序主要由一个活动与许多片段和一对服务组成。从正在进行的通知中启动活动第二次崩溃

这是我用来显示和更新通知的方法。它在一个名为Notifications.java的类中实现。 它的方法在MainActivity的onResume中以及接收消息的服务中调用。

public static void updateOngoingNotification(Context c, String text) { 
    Intent intent = new Intent(c, MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    PendingIntent pIntent = PendingIntent.getActivity(c, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setOngoing(true) 
      .setContentText(text) 
      .setContentTitle(c.getString(R.string.app_name)) 
      .setContentIntent(pIntent); 

    NotificationManager notificationManager = (NotificationManager) c 
      .getSystemService(c.NOTIFICATION_SERVICE); 
    notificationManager.notify(0, mBuilder.build()); 
} 

的问题是,这一切似乎工作,因为它应该,但是当我尝试启动活动第二次,应用程序冻结。我怀疑通知ID或丢失的标志,但迄今没有找到解决方案的运气。

+0

它是否崩溃或你得到任何日志? –

回答

2

当你的活动是singleTop或者您在IntentFLAG_ACTIVITY_SINGLE_TOP标志调用它,新Intent对象将被传递到您的活动的onNewIntent方法,如果它已经在运行。因此,您需要在您的活动中覆盖onNewIntent方法,该方法将从通知中接收新的Intent对象。所以,你可以相应地更新你的活动。

Ref:http://developer.android.com/intl/es/reference/android/app/Activity.html#onNewIntent(android.content.Intent)

+0

谢谢你的快速回答。它的工作,但我不得不将标志设置为\t \t intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); 这不是我上面发布的代码的一部分。不过,这个解决方案对我的应用程序很有用。谢谢! :) – Alex

+0

很高兴帮助你:) –

相关问题