通过意图发送数组?

时间:2014-08-22 15:59:18

标签: android arrays android-intent parcelable

我正在尝试将一组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);
}

通过意图接收数组的服务:

@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 doc here)已经实现了Parcelable,因此我应该能够通过意图发送它的所有内容,对吗?

非常感谢一些帮助,因为我被困住了,谢谢

2 个答案:

答案 0 :(得分:2)

相反

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

呼叫

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

答案 1 :(得分:1)

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

基本上你采用Parcelable数组,迭代它,然后通过在迭代时强制转换项目将项目复制到StatusBarNotification数组中。