REG1
REG1

Reputation: 486

Send array through intent?

I am trying to send an array of StatusBarNotifications to another service of mine so I have tried this:

Service that extends 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);
}

Service to receive array through 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
}

Edit

However I get a ClassCastException(marked above with comment)

Here is the log:

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[]

I read quite a bit about sending objects through intents and about implementing Parcelable, although it was pretty complicated, see here for example. But from what I can see StatusBarNotification (see API doc here) already implements Parcelable, thus I should be able to send it through an intent with all of its content, right?

Would really appreciate some help here as I am stuck, thanks

Upvotes: 0

Views: 327

Answers (2)

Damian Petla
Damian Petla

Reputation: 9103

Instead

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

call

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

Upvotes: 2

Daniel Zolnai
Daniel Zolnai

Reputation: 16910

For the ClassCastException, see: I don't get why this ClassCastException occurs

Basically you take the Parcelable array, iterate over it, and copy the items into a StatusBarNotification array by casting the items while iterating.

Upvotes: 1

Related Questions