Mar*_*lon 2 android instant-run
我正在运行Android Studio 2.0的新稳定版.当我禁用即时运行我的应用程序运行正常,但当我打开它时它给了我这个错误:
Caused by: java.lang.ClassCastException: com.android.tools.fd.runtime.BootstrapApplication cannot be cast to com.my.app.CustomApplication
Run Code Online (Sandbox Code Playgroud)
CustomApplication是我通过上下文获取的Application类.但我似乎无法得到它.当启用即时运行时,我的类被转换为BootstrapApplication然后失败.
我的应用程序是像FB chatheads这样的浮动服务.
我有最新的gradle构建:
classpath 'com.android.tools.build:gradle:2.0.0'
Run Code Online (Sandbox Code Playgroud)
这里的其他答案说,即时运行尝试进行热交换代码; 这会导致应用程序类被移动.
那我怎么能解决这个问题呢?
解决方案#1 - 在"设置"中禁用即时运行
解决方案#2 - 使用反射从BootstrapApplication获取实际应用程序
public static CustomApplication getRealApplication (Context applicationContext)
{
CustomApplication application = null;
if (applicationContext instanceof CustomApplication)
{
application = (CustomApplication) applicationContext;
}
else
{
Application realApplication = null;
Field magicField = null;
try
{
magicField = applicationContext.getClass().getDeclaredField("realApplication");
magicField.setAccessible(true);
realApplication = (Application) magicField.get(applicationContext);
}
catch (NoSuchFieldException e)
{
Log.e(TAG, e.getMessage());
}
catch (IllegalAccessException e)
{
Log.e(TAG, e.getMessage());
}
application = (CustomApplication) realApplication;
}
return application;
}
Run Code Online (Sandbox Code Playgroud)
在某处使用:
Context applicationContext = getContext().getApplicationContext();
CustomApplication application = getRealApplication(applicationContext);
Run Code Online (Sandbox Code Playgroud)
使用示例:
public class MyProvider extends OrmLiteProvider<OrmLiteSqliteOpenHelper, OrmLiteUriMatcher<OrmLiteMatcherEntry>>
{
@Override
protected OrmLiteSqliteOpenHelper createHelper ()
{
Context applicationContext = getContext().getApplicationContext();
CustomApplication application = CustomApplication.getRealApplication(applicationContext);
return application.getComponent().databaseHelper();
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1307 次 |
| 最近记录: |