【问题标题】:Send array through intent?通过意图发送数组?
【发布时间】:2014-08-22 15:59:17
【问题描述】:

我正在尝试将一组 StatusBarNotifications 发送到我的另一个服务,所以我尝试了这个:

扩展NotificationListenerService的服务:

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    // TODO Auto-generated method stub
    StatusBarNotification[] activeN = super.getActiveNotifications();               

    Intent i = new Intent("com.project.now.CORETWO");
    i.putExtra("activenotfications", activeN);
    startService(i);
}

服务通过intent接收数组:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    Log.i("abc", "onStartCommand"); 
    activeNotifications = (StatusBarNotification[]) intent.getParcelableArrayExtra("activenotifications"); //This line throws exception
}

编辑

但是我收到了ClassCastException(上面标有评论)

这是日志:

08-22 22:49:22.319: E/AndroidRuntime(20801): FATAL EXCEPTION: main
08-22 22:49:22.319: E/AndroidRuntime(20801): Process: com.project.now, PID: 20801
08-22 22:49:22.319: E/AndroidRuntime(20801): java.lang.RuntimeException: Unable to start service com.project.now.CoreTwo@425ed8d0 with Intent { act=com.project.now.CORETWO (has extras) }: java.lang.ClassCastException: android.os.Parcelable[] cannot be cast to android.service.notification.StatusBarNotification[]

我读过很多关于通过意图发送对象和implementing Parcelable 的文章,虽然它相当复杂,例如参见here。但据我所知,StatusBarNotification(参见 API 文档here)已经实现了 Parcelable,因此我应该能够通过 Intent 发送它的所有内容,对吧?

在我遇到困难时非常感谢您的帮助,谢谢

【问题讨论】:

标签: android arrays android-intent parcelable


【解决方案1】:

相反

activeNotifications = (StatusBarNotification[]) intent.getExtras().get("activenotifications");

打电话

Parcelable[] parcelable = intent.getParcelableArrayExtra("activenotifications");
StatusBarNotification[] sbn = Arrays.copy(parcelable, parcelable.lenght, StatusBarNotification[].class);

【讨论】:

  • 感谢您的建议,但我仍然在同一点收到 NullPointerException。知道为什么会这样吗?
  • 我意识到我拼错了标签(它们不匹配),这是一个愚蠢的错误。但是,当我尝试接收意图时(请参阅我的代码),我仍然会收到异常 (ClassCastException)。如果您能再看一遍,将不胜感激,再次感谢
  • 我的回答有点着急。当然,这种铸造是行不通的。您已经从其他人那里得到了正确的答案,但我已经更新了我的答案,以使其对其他 SO 访问者来说是完整且有用的。
【解决方案2】:

对于ClassCastException,请参阅:I don't get why this ClassCastException occurs

基本上,您获取 Parcelable 数组,对其进行迭代,然后通过在迭代时强制转换项目将项目复制到 StatusBarNotification 数组中。

【讨论】:

  • 感谢您的回答,我使用了 Arrays.copyOf() 方法,该方法似乎为我完成了整个过程(由 Brodo Fraggins 建议)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 2021-11-18
  • 2018-10-18
  • 2015-06-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多