ClassCastException: Application object is not my c

2019-08-18 18:39发布

Often in Android code we use this pattern of storing data in the Application object and then accessing it via casting as such:

((MyApplicationObject)getApplication()).getDaggerComponent()

getApplication() should always be MyApplicationObject because I have specified it in the AndroidManifest.xml. However, when you deploy this code, sometimes it causes a ClassCastException and we get a different object instead.

How can this be?

What is the correct workaround for this issue?

1条回答
家丑人穷心不美
2楼-- · 2019-08-18 18:55

Resolved in the comments: this is an Android bug, not one related to Dagger.

Thank you for that link! 98% of the crashes are from Android 7.0, with 0.2% from Android 7.1. In the link a @google engineer says they improved things in major issues in 7.0, but didn't completely fix it. – gregm

See this public Google IssueTracker link, #37137009: java.lang.ClassCastException: Cannot cast android.app.Application to com.xxx.xxApplication (ctate's comment in #17):

Yes, this is a known issue; and was largely addressed in 7.1. There are still some edge cases in 7.1 that can result in similar circumstances -- as you can see from your analytics -- but the window of opportunity is much narrower, and Android 8 addressed those as well.

Unfortunately, for the time being, there doesn't seem to be much of an explanation or official workaround, but at least the issue is predominantly limited in scope to Android 7.0.

查看更多
登录 后发表回答