ClassCastException 在执行我的应用程序时使用 minifyEnabled true



我有一个Android系统应用程序,它在清单中有一个自定义的BroadCastReceiver(这将在Android M设备中运行(: 我的清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system"
package="mypackagename">
....
<!-- custom permissions -->
<uses-permission android:name="mypackagename.ASK_DISPLAY_INFO"
android:protectionLevel="signatureOrSystem"/>
<permission android:name="mypackagename.ASK_DISPLAY_INFO" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

....
<!-- custom receiver -->
<receiver android:name=".CustomReceiver"
android:permission="mypackagename.ASK_DISPLAY_INFO">
<intent-filter>
<action android:name="GET_HDMI_SUPPORTED_MODES"/>
<action android:name="CHANGE_HDMI_RESOLUTION"/>
</intent-filter>
</receiver>

</application>
</manifest>

我已经在gradle Proguard中启用了混淆:

release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

}

我有另一个测试应用程序,可以将广播发送到此应用程序。问题是,使用 mignifyEnabled false 有效,但使用 mignifyEnabled true 时收到广播意图时,它会给出错误:

java.lang.RuntimeException:无法实例化接收器 mypackagename。CustomReceiver: java.lang.ClassCastException: mypackagename.CustomReceiver 不能投射到 android.content.BroadcastReceiver

将以下规则添加到 proguard-rules.pro:

-keep class android.content.BroadcastReceiver { *; }

收到意图时会引发错误:

java.lang.AbstractMethodError: abstract Method "void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent(">

这是我的广播接收器定义:


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class CustomReceiver extends BroadcastReceiver {
...
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
Log.i(TAG, "CustomReceiver received action: "+intent.getAction());
if (intent.getAction().equals(GET_HDMI_SUPPORTED_MODES)) {
new GetHDMIModesTask(context).execute();
}  else if (intent.getAction().equals(CHANGE_HDMI_RESOLUTION) && intent.getExtras() != null && intent.hasExtra(EXTRA_HDMI_MODE) ) {
new ChangeHDMIModeTask(context, intent.getStringExtra(EXTRA_HDMI_MODE)).execute();
}
}
}
}

由于我对 Proguard 规则非常陌生,我需要对此进行混淆,如果有人可以告诉我可以指定哪些规则来解决此问题,我将不胜感激

-keep public class * extends android.content.BroadcastReceiver添加到您的保护规则中,而不是-keep class android.content.BroadcastReceiver { *; }。这将防止您的自定义广播接收器被混淆。

我对此做了一个解决方法,从清单中删除了 CustomerReceiver,添加了一个自定义应用程序类并在其中定义了 BroadcastReceiver。添加了保护规则:

-keep class android.app.Application {
public <fields>;
private <fields>;
public <methods>;
}
-keep public class * extends android.app.Application

问题消失了

最新更新