我有一个CustomApplication extends Application
课程,已在AndroidManifest
<application
....
// Please, pay attention that I got this in my Manifest
android:name=".CustomApplication">
在我的应用程序的不同部分,我做了一些活动和服务
getApplication()/getApplicationContext()
然后将其转换为CustomApplication
,并且由于类强制转换异常,它会在各种设备/ sdk版本(从android 6开始)的生产中崩溃。 Caused by: java.lang.ClassCastException
示例:
class CustomApplication extends Application{
...
public static CustomApplication with(Context context) {
return (CustomApplication) context.getApplicationContext(); //crashes here
}
}
和服务示例:
class CustomService extends IntentService{
...
@Override
rotected void onHandleIntent(@Nullable Intent intent) {
CustomApplication app = CustomApplication.from(getApplication());
// tried getApplicationContext() also
}
}
和活动示例:
class CustomActivity extends AppCompatActivity{
...
@Override
protected void onCreate(...){
CustomApplication app = CustomApplication.with(this);
}
我尝试过的事情:
process=":process"
launchModes
taskAffinity
没有什么能帮助我在模拟器上重现问题
我也不使用Instant Run
(从未使用过它)
请不要向我提供使用static application context instance
答案 0 :(得分:0)
您可以保留CustomApplication
的静态参考,如下所示。您无需按以下方式进行投射。
public class CustomApplication extends Application {
private static CustomApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static CustomApplication getContext() {
return instance;
}
}
然后拨打CustomApplication.getContext();
答案 1 :(得分:0)
您需要在清单中定义自定义应用程序,如下所示:
<application
....
android:name="my.package.path.CustomApplication">
... activities ....
</application>
此外,您正在获取一个扩展Application
而不是Context
的类的实例,据说您应该通过以下方式调用它:
CustomApplication customApplication;
customApplication = (CustomApplication)getApplication();
如果您有BroadcastReceiver(无上下文可用),您可能需要申请的是:
customApplication = (CustomApplication)getApplicationContext().getApplication();