我在 Android 4.4.4 上制作了一个 Android 应用程序,我想在 Android 4.0.0 上开发它。我在将服务(我的 Binder )发送到 fragment 时遇到问题。
在 Android 4.4.4 上,我使用以下行:
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();
但是当我尝试使用 Android 4.0.0 构建我的项目时出现以下错误: 调用需要 API 级别 18(当前最低为 14):android.os.Bundle#putBinder less (Ctrl + F1)
当我尝试在 Ice Scream Sandwich 上构建我的项目时,我不明白如何将我的服务、我的 Binder 发送到 fragment 。
最佳答案
因为 Bundle.putBinder()
是 API 18+,所以您必须以不同的方式进行。最简单的方法是让您的 Fragment
定义一个您的 Activity
必须实现的回调接口(interface):
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;
}
}
关于android - 如何通过 Binder 将服务发送到 API 级别 14 上的 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460699/