无法将应用程序强制转换为CustomApplication

时间:2017-10-16 13:15:36

标签: android

我有一个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
  • 进行的活动
  • 从推送通知启动
  • 使用系统托盘(在设备上)清理流程,ps kill int adb shell

没有什么能帮助我在模拟器上重现问题

我也不使用Instant Run(从未使用过它)

请不要向我提供使用static application context instance

的建议

2 个答案:

答案 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();