Android EventBus异常处理总结

1、java.lang.ClassNotFoundException:Didn't find class "android.os.PersistableBundle" on path: /data/app/cn.com.hushayunlian.logistics.driver-1.apk

解答:

经查阅官方资料,得知解决方案,如下所示:

A java.lang.NoClassDefFoundError is throw when a subscriber class is registered. What can I do?
First a bit of background to help you understand what’s going on here: Some Android versions seem to have a bug with reflection when calling getDeclaredMethods or getMethods. The exception is thrown if the class has methods with a parameter that is unavailable to the API level of the device. For example, the class PersistableBundle was added in API level 21. Along with the new class some new life cycle methods were introduced in the class Activity having PersistableBundle as a parameter, for example onCreate (Bundle savedInstanceState, PersistableBundle persistentState). Now, if you override this method and you try to register this Activity to EventBus on a older device, we have exactly the scenario described to cause to bug. Understanding why this happens will help to resolve the issue easily.

Here are a couple suggestions how to fix the scenario (check in given the order):

Maybe you overwrote a life cycle method with PersistableBundle just by accident. In that case just change to the method without PersistableBundle, for example onCreate (Bundle savedInstanceState).
Use EventBus 3 with an subscriber index. This will avoid reflection and thus the problem altogether. As a positive side effect, registering subscribers and thus app startup time will be much faster.
Remove the offending method from your subscriber class. Either pull out the event handler methods into a new subscriber class, or pull out the offending method into a non-subscriber class.
If the offending method is public, make it non-public. This works because of some “plan b” logic EventBus applies: EventBus first calls getDeclaredMethods, which will fail. Next, EventBus will try again using the getMethods (“plan b”). The latter will succeed because getMethods only returns public methods. However, keep in mind that is the least efficient way in terms of performance (2 reflection calls instead of 1 with getMethods considering the entire class hierarchy).

综上所述,eventbus官方对常见的异常不仅做出解释,而且给出解决方案。去掉API21的savedInstanceState方法,onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)。保留API1的savedInstanceState方法,onSaveInstanceState(Bundle outState)。

你可能感兴趣的:(Android EventBus异常处理总结)