首先,在build.gradle(:app)中链接framework.jar包
dependencies {
compileOnly files("libs/framework.jar")
implementation libs.appcompat
implementation libs.material
implementation libs.constraintlayout
implementation libs.activity
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
}
然后,因为Android Studio有自带的android.jar跟framework.jar共用系统标准类,同名情况下优先链接android.jar包的,而不是framework.jar包的,所以需要让framework.jar包更早链接,有如下两种改法:
改法一:
gradle.projectsEvaluated {
tasks.withType(JavaCompile).tap {
configureEach {
options.compilerArgs.add("-Xbootclasspath/p:$rootProject.rootDir/app/libs/framework.jar")
}
}
}
改法二:
gradle.projectsEvaluated {
tasks.withType(JavaCompile).tap {
configureEach {
Set<File> fileSet = options.bootstrapClasspath.getFiles()
List<File> newFileList = new ArrayList<>();
//JAVA语法,可连续调用,输入参数建议为相对路径
newFileList.add(new File("libs/framework.jar"))
//最后将原始参数添加
newFileList.addAll(fileSet)
options.bootstrapClasspath = files(
newFileList.toArray()
)
}
}
}
通过下面的代码测试:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
**int bbb = WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
Log.e("Test", "onCreate: " + bbb);**
}
}
上述修改后,编译不会报错,但是不在android.jar中的方法仍然会显示为红色,如下图:
这种情况网上有提供一种方法,即在build.gradle(:app)中添加如下修改:
preBuild {
doLast {
def rootProjectName = rootProject.name.replace(" ", "_")
def projectName = project.name.replace(" ", "_")
def iml_path = "$rootProject.rootDir\\.idea\\modules\\" + projectName + "\\" + rootProjectName + "." + projectName + ".main.iml"
def imlFile = file(iml_path)
try {
def parsedXml = (new XmlParser()).parse(imlFile)
def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' }
def sdkString = jdkNode.'@jdkName'
parsedXml.component[1].remove(jdkNode)
new Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK'])
groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile))
} catch (FileNotFoundException e) {
e.printStackTrace()
}
}
}
这会将.idea/modules/app/XXX.app.main.xml(XXX是ProjectName,根据自己的修改)中的
<orderEntry type="jdk" jdkName="Android API 34, extension level 7 Platform" jdkType="Android SDK" />
从前面调整到最后面(其实也可以手动调整)
这样使用framework.jar中独有的接口就不会显示红色了。如果出现需要重新设置SDK、JDK的情况,重启一下Android Studio就好了。