无法将字符串解析为通知活动

时间:2015-01-19 17:27:44

标签: android notifications push-notification android-notifications

我有一个ExternalReceiver类,它接收来自服务的通知:

public class ExternalReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        if(intent!=null){
                MessageReceivingService.saveToLog(intent, context);            
        }
    }
}

调用的saveToLog方法存储通知消息:

protected static void saveToLog(Intent intent, Context context)
 {

    String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);

    final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent exintent = new Intent (context, NotificationActivity.class);     
    intent.putExtra("NotificationMessage", newMessage);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, exintent, PendingIntent.FLAG_UPDATE_CURRENT);
    final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Besked fra Salon")
            .setContentText(newMessage)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .getNotification();


    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notification.defaults |= Notification.DEFAULT_SOUND;

    mNotificationManager.notify(R.string.notification_number, notification);              
 }

到目前为止它工作正常,因为我的手机会显示带有消息的通知。但是当我点击通知时,它会进入NotificationAcivity类:

public class NotificationActivity extends Activity {
TextView textViewAc;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification);

    textViewAc = (TextView) findViewById(R.id.textViewAc);
            findViewById(R.id.textViewr1n1);

    onNewIntent(getIntent());               
}

@Override
public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    if(extras != null){
        if(extras.containsKey("NotificationMessage"))
        {
            // extract the extra-data in the Notification
            String msg = extras.getString("NotificationMessage");
            textViewAc.setText(msg);    
        }
    }


  }
}

intent中的“extras”值为null,因此实际上并未存储“newMessage”字符串。为什么在这种情况下不存储值?

1 个答案:

答案 0 :(得分:1)

您似乎将exintent设置为NotificationActivity并将putextra添加到intent,因此更改

  intent.putExtra("NotificationMessage", newMessage);
  intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

  exintent.putExtra("NotificationMessage", newMessage);
  exintent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);