将ArrayList <string>从BroadCastReceiver发送到Activity </string>

时间:2012-03-12 19:20:29

标签: android android-activity arraylist broadcastreceiver bundle

情境:

  • 我有一个警报计划在指定的时间内运行。每次执行,我的BroadCastReceiver都会触发。

  • 在BroadCastReceiver中,我做了所有类型的检查,最终得到了一个简单字符串的ArrayList

  • 我在状态栏上显示通知

  • 当用户点按通知时,我会显示一个活动。我需要在我的Activity中,ArrayList在视图上显示它。

以下是示例代码:

public class ReceiverAlarm extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         ArrayList<String> notifications = new ArrayList<String>();

         //do the checks, for exemplification I add these values
         notifications.add("This is very important");
         notifications.add("This is not so important");
         notifications.add("This is way too mimportant");

         NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
         //init some values from notificationManager
         Intent intentNotif = new Intent(context, NotificationViewer.class);
         PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intentNotif, 0);

         Notification notification = new Notification(icon, text, when);
         notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
         notificationManager.notify(NOTIFICATION_ID, notification);
    }

并且

   public class NotificationViewer extends Activity {


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

                   //HERE I NEED the ArrayList<String> notifications
    }

我尝试了大多数我发现的东西,从bundle到putStringArrayListExtra(),但没有任何效果。在我的活动中,我无法找到检索数据的方法。 我被困住了,请帮助我。

3 个答案:

答案 0 :(得分:1)

根据我的建议,您可以通过两种方式快速收到它:

  1. 创建实现Percelable的自定义类,并将自己的实现设计为Write和Read parcelable对象。
  2. 使用Gson将对象序列化为单个json字符串,将其包装在intent中,在另一端接收它并将Json字符串反序列化为所需的对象类型
  3. 可能还有其他一些方法,比如将ArrayList序列化为字节并将其写入文件并稍后阅读,但这两种方法是我建议您处理任何类型信息的最佳方法。就个人而言,我喜欢第二个,使用Gson让它自己处理所有事情。

答案 1 :(得分:1)

根据标记为解决方案HERE的答案,如果您未指定针对待处理意图的操作,则不会传播额外内容

答案 2 :(得分:0)

基于所有评论,工作解决方案是:

BroadCastReceiver上的

Intent intentNotif = new Intent(context, NotificationViewer.class);
intentNotif.putStringArrayListExtra("list", notifications);

on Activity

Bundle b = getIntent().getExtras();
if (b != null) {
    testArrayList= b.getStringArrayList("list");
}

这似乎工作正常。