RemoteCallback.java revision 9c165d76010d9f79f5cd71978742a335b6b8d1b4
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import android.annotation.NonNull; 20import android.annotation.Nullable; 21 22/** 23 * @hide 24 */ 25public final class RemoteCallback implements Parcelable { 26 27 public interface OnResultListener { 28 public void onResult(Bundle result); 29 } 30 31 private final OnResultListener mListener; 32 private final Handler mHandler; 33 private final IRemoteCallback mCallback; 34 35 public RemoteCallback(OnResultListener listener) { 36 this(listener, null); 37 } 38 39 public RemoteCallback(@NonNull OnResultListener listener, @Nullable Handler handler) { 40 if (listener == null) { 41 throw new NullPointerException("listener cannot be null"); 42 } 43 mListener = listener; 44 mHandler = handler; 45 mCallback = new IRemoteCallback.Stub() { 46 @Override 47 public void sendResult(Bundle data) { 48 RemoteCallback.this.sendResult(data); 49 } 50 }; 51 } 52 53 RemoteCallback(Parcel parcel) { 54 mListener = null; 55 mHandler = null; 56 mCallback = IRemoteCallback.Stub.asInterface( 57 parcel.readStrongBinder()); 58 } 59 60 public void sendResult(@Nullable final Bundle result) { 61 // Do local dispatch 62 if (mListener != null) { 63 if (mHandler != null) { 64 mHandler.post(new Runnable() { 65 @Override 66 public void run() { 67 mListener.onResult(result); 68 } 69 }); 70 } else { 71 mListener.onResult(result); 72 } 73 // Do remote dispatch 74 } else { 75 try { 76 mCallback.sendResult(result); 77 } catch (RemoteException e) { 78 /* ignore */ 79 } 80 } 81 } 82 83 @Override 84 public int describeContents() { 85 return 0; 86 } 87 88 @Override 89 public void writeToParcel(Parcel parcel, int flags) { 90 parcel.writeStrongBinder(mCallback.asBinder()); 91 } 92 93 public static final Parcelable.Creator<RemoteCallback> CREATOR 94 = new Parcelable.Creator<RemoteCallback>() { 95 public RemoteCallback createFromParcel(Parcel parcel) { 96 return new RemoteCallback(parcel); 97 } 98 99 public RemoteCallback[] newArray(int size) { 100 return new RemoteCallback[size]; 101 } 102 }; 103} 104