Search code examples
androidandroid-fragmentsandroid-binder

How to send a service via a binder to a fragment on API level 14?


I have made an Android app, on Android 4.4.4, and I want to develop it on Android 4.0.0. I have a problem to send a service, my binder, to a fragment.

On Android 4.4.4 I use the following lines :

AddTrashFragment addTrashFragment = new AddTrashFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap2);
bundle.putString("fileName", fileName);
bundle.putBinder("binder", binder);
addTrashFragment.setArguments(bundle);

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.relativeLayout,addTrashFragment).addToBackStack(null).commitAllowingStateLoss();

But when I try to build my project with Android 4.0.0 I have the following error : Call requires API level 18 (current min is 14): android.os.Bundle#putBinder less (Ctrl + F1)

I don't understand how to send my service, my binder, to a fragment when I try to build my project on Ice Scream Sandwich.


Solution

  • Because the Bundle.putBinder() is API 18+ you'll have to do it a different way. The simplest is to have your Fragment define a callback interface which your Activity must implement:

    public class MyFragment extends Fragment {
        MyFragment.Callback  cb;
    
        public interface Callback {
            Binder getServiceBinder();
        }
        ...
    
        public void onAttach(Context context) {
            try {
                cb = (MyFragment.Callback)context;
            } catch (ClassCastException e) {
                Log.e(TAG, "Activity (Context) must implement Callback");
                throw new RuntimeException();
            }
        }
    }
    
    public class MyActivity extends Activity implements MyFragment.Callback {
        private Binder  mService;
        ...
    
        public Binder getServiceBinder() {
            return mService;
        }
    }