在 Mi 9 手机上使用 Xiaomis MIUI 10 时,其他答案均不适合我。
除了通常的(例如在开发者选项中启用USB debugging 和Install via USB),其他问题的答案建议关闭MIUI optimization。虽然这起到了作用,但我对此并不满意。所以我做了一些挖掘,得出了以下结论:
所述错误仅在您第二次部署应用时发生,之后在将同一应用部署到该手机时每隔一次发生一次。
要解决这个问题,我可以再次点击 Run / 按 Shift + F10 或拔下电话并再次插入。这些似乎都不可行。因此,我进行了更多挖掘,结果发现,当您每次构建应用程序时都在 build.gradle 文件中增加 versionCode 时,MIUI 10 不会抱怨并让您按照预期安装应用程序。甚至 Android Studios Instant Run 也能正常工作。虽然手动执行此操作同样烦人。
所以我采取了一些想法,从this question 自动增加versionCode 并修改了build.gradle(用于您的模块,而不是用于您的项目)。您可以按照以下简单步骤执行相同操作:
替换
defaultConfig {
applicationId "your.app.id" // leave it at the value you have in your file
minSdkVersion 23 // this as well
targetSdkVersion 28 // and this
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
与
def versionPropsFile = file('version.properties')
def value = 0
Properties versionProps = new Properties()
if (!versionPropsFile.exists()) {
versionProps['VERSION_MAJOR'] = "1"
versionProps['VERSION_MINOR'] = "0"
versionProps['VERSION_PATCH'] = "0"
versionProps['VERSION_BUILD'] = "0"
versionProps.store(versionPropsFile.newWriter(), null)
}
def runTasks = gradle.startParameter.taskNames
if ('assembleRelease' in runTasks) {
value = 1
}
if (versionPropsFile.canRead()) {
versionProps.load(new FileInputStream(versionPropsFile))
versionProps['VERSION_PATCH'] = (versionProps['VERSION_PATCH'].toInteger() + value).toString()
versionProps['VERSION_BUILD'] = (versionProps['VERSION_BUILD'].toInteger() + 1).toString()
versionProps.store(versionPropsFile.newWriter(), null)
// change major and minor version here
def mVersionName = "${versionProps['VERSION_MAJOR']}.${versionProps['VERSION_MINOR']}.${versionProps['VERSION_PATCH']}"
defaultConfig {
applicationId "your.app.id" // leave it at the value you have in your file
minSdkVersion 23 // this as well
targetSdkVersion 28 // and this
versionCode versionProps['VERSION_BUILD'].toInteger()
versionName "${mVersionName} Build: ${versionProps['VERSION_BUILD']}"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
else {
throw new GradleException("Could not read version.properties!")
}
现在,每次您通过点击Run 或Instant Run 构建应用程序时,您的versionCode / VERSION_BUILD 都会增加。
如果您构建一个版本,您的VERSION_PATCH 也会增加,同时将您的versionName 从x.y.z 更改为x.y.z+1(即1.2.3 变为1.2.4)。要更改VERSION_MAJOR(x)和VERSION_MINOR(y),请编辑您可以在模块文件夹中找到的version.properties 文件。如果您没有更改模块名称,则它称为app,因此此文件位于app/version.properties。