Failure [INSTALL_FAILED_USER_RESTRICTED: Invalid apk] in android - android

I am using Android Studio 3.0.1.
When i am trying to run app
INSTALL_FAILED_USER_RESTRICTED: Invalid apk
error occurs.
I also disable Instant Run.
again i am run app but same error occurs.
04/04 10:59:08: Launching app
$ adb push G:\Android\Fundraiser\BuyForFund\app\build\outputs\apk\debug\app-debug.apk /data/local/tmp/com.android.buyforfund
$ adb shell pm install -t -r "/data/local/tmp/com.android.buyforfund"
Failure [INSTALL_FAILED_USER_RESTRICTED: Invalid apk]
$ adb shell pm uninstall com.android.buyforfund
DELETE_FAILED_INTERNAL_ERROR
Error while Installing APK

None of the other answers worked for me using Xiaomis MIUI 10 on a Mi 9 phone.
Besides the usual (like enabling USB debugging and Install via USB in the developer options) answers from other questions suggested turning off MIUI optimization. While this did the trick, I wasn't happy with it. So I did some digging and came to the following conclusions:
The described error only occurred the second time you deploy your app and after that keeps occurring every other time when deploying the same app to that phone.
To solve this I could either hit Run / press Shift + F10 again or unplug and plug in that phone again. None of this seems viable. So I did some more digging and it turns out when you are increasing the versionCode in your build.gradle file every time you build your app, MIUI 10 will not complain and let you install your app just like you would expect. Even Android Studios Instant Run works. Though doing this manually is just as annoying.
So I took some ideas to auto-increment the versionCode from this question and modified build.gradle (the one for your module, NOT the one for your project). You can do the same following these easy steps:
Replace
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"
}
with
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!")
}
Now each time you build your app by hitting Run or Instant Run your versionCode / VERSION_BUILD increases.
If you build a release your VERSION_PATCH increases as well changing your versionName from x.y.z to x.y.z+1 (i.e. 1.2.3 turns to 1.2.4). To change VERSION_MAJOR (the x) and VERSION_MINOR (the y) edit the version.properties file which you can find in your module folder. If you didn't change your modules name it's called app so this file is located at app/version.properties.

Make sure you have enabled the following options:
Settings > Additional Settings > Developer options
USB Debugging
Install via USB
USB Debugging (Security settings)

I have the same problem, I sent a feedback to Google on my phone, would say it's a bug. In my case the best solution is to cancel that dialog and then re-run, it works always on second attempt after cancelling.
Depending on what phone you are using, I would assume the problem is on the phone (Google) side. Not sure yet if a general Google problem or specific hardware phones, I use "Xiaomi Redmi 5".
Disabling instant run actually worked in my case, but that's not the purpose of it, that's just a dirty workaround.
Edit:
Make sure that you don't have something like
android:debuggable="false"
in your manifest.

I ran into this same error while the underlying issue was different.
Mine was that I was trying to install my app on Android 12 device while the AndroidManifest.xml file didn't have all the android:exported properties explicitly set. This error is explained further here: https://developer.android.com/about/versions/12/behavior-changes-12#exported
If your app targets Android 12 or higher and contains activities,
services, or broadcast receivers that use intent filters, you must
explicitly declare the android:exported attribute for these app
components.
Warning: If an activity, service, or broadcast receiver uses intent
filters and doesn't have an explicitly-declared value for
android:exported, your app can't be installed on a device that runs
Android 12 or higher.
After I added the required android:exported properties into AndroidManifest.xml file, the error was resolved.

In your Androidmanifest.xml file at path
app/src/main/Androidmanifest.xml
add android:exported="true"` in activity tag.
Sample:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example">
<application
android:label="example"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
android:exported="true">

For those who still might get this error if you have done everything from enabling to flutter clean and all.
I solved this error by checking the manifest and adding proper value because i changed something in the manifest which was not supported and later forgot to change it.
so if you have changed something in theme, drawable or any resource file check that out first.

INSTALL_FAILED_USER_RESTRICTED: Invalid apk
Steps for MIUI 9 and Above:
Settings -> Additional Settings -> Developer options ->
step 1: scroll down side - Turn off "MIUI optimization" and Restart your device.
step 2: Turn On "USB Debugging"
step 3: Turn On "Install via USB"
step 4: show push notification and just click USB - Set USB Configuration to Charging (MTP(Media Transfer Protocol) is the default mode.
Works even in MTP in some cases).
please try.

If you are targeting android 'P' then your build.gradle file should look like this
android {
compileSdkVersion 'android-P'
defaultConfig {
applicationId "xyz.com"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
targetSdkVersion must be 27 to run your app below android 'P', otherwise the app can only run on 'P' and above.

Related

Version code 1 has already been used. Try another version code

I am uploading new app bundle to play console and it is saying after uploading Version code 1 has already been used. Try another version code.
I have changed version number in pubspec.yaml from version number: 1.0.0+1 to 2.0.0+1 even though it is saying the same error
You have two ways to solve this, if you released your bundle already, then you have to update your version code like in Len_X's answer,
If you're still developing and pushed app bundle for say, testing, and then you delete it, this bundle is saved as a draft with that version code. Therefore, it says that you can't use the same version because it already sees another one with the same version name.
Here's how you fix it:
Go to the release section
go to app bundle explorer, in the top right you should see a dropdown button for you app version, click on it.
A bottomsheet will show containing all the previous app bundles you uploaded it. Delete the one with clashing bundle version and you're good to go.
Hope that solves your problem.
You can do it manually by going to "app_name/android/app/build.gradle" file. In defaultConfig section change version code to a higher number
defaultConfig {
applicationId "com.my.app"
minSdkVersion 23
targetSdkVersion 30
versionCode 1 // Change to a higher number
versionName "1.0.1" // Change to a higher number
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
First go to the app/build.gradle
change versionCode and versionName like this (+1)
I think this will be helpful for someone ✌😊
For Flutter only:
Goto Pubspec.yaml file and find version key and Change the value after the + sign.
For Example:
In your pubspec.yaml file, if your version is like this version: 1.0.0+1 then change it to version: 1.0.0+2
You have to increment the +1, it should be +2 to indicate build number
if you remove apk then upload same version apk so you get Error Version code 1 has already been used. Try another version code in this situation you should remove version from App bundle explorer then upload same version apk.
If you're running into app bundle approval issues inside of the Google Play store with an Expo/React Native project, here are some tips:
Google Play versioning is actually checking your AndroidManifest.xml file for versioning (/android/app/src/). This should get updated from Expo's app.json file (/app.json) during build, per their instructions.
app.json example section, where I've bumped my app up to a v2.0 - note the versionCode inside of the Android settings object AND the version at the settings object root both need to be adjusted:
{
"name": "app-name",
"displayName": "App Name",
"expo": {
"android": {
"package": "app.here",
"permissions": [],
"versionCode": 2
}
},
"version": "2.0.0"
}
If your Android version isn't updating (possibly if you have a detached Expo app), you have to go directly into the AndroidManifest.xml file and make the modification there (/android/app/src/):
Example of AndroidManifest.xml (note your modifications happen on the <manifest> tag, using the android:versionCode and android:versionName:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aganashapp"
android:versionCode="2"
android:versionName="2.0"
>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:allowBackup="false"
android:theme="#style/AppTheme"
>
<meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="https://exp.host/#username/app-name" />
<meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="42.0.0" />
<meta-data android:name="expo.modules.updates.EXPO_RELEASE_CHANNEL" android:value="default" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:theme="#style/Theme.App.SplashScreen"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
</application>
</manifest>
If you're still having issues, remember that Android versionCode and versionName are two different things. Android does not seem to recognize semver standards. versionCode increments as whole numbers (ie, if you went from semver v1.0.0 to v1.1.0 that is versionCode 1 to 2.
with my flutter project building a release for android i faced the same issue. all was doing is change version code in Pubspec.yaml but did not seem to change my android version...
so i went to Android folder and added version code manually in local.properties file :
/project/android/local.properties
flutter.versionName=1.1.0
flutter.versionCode= from 1 to 4
I always used to increment version code in my android/app/build.gradle file, and it always used to work. Then, after a recent update in Android Studio, it suddenly didn't anymore, and I got this error!
I never cared to dig into the build.gradle code, but now, I did. Here, at the "TODO", is where I used to change the version code number:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '19' // TODO: ---Count up with each release
}
But that only works if the version code from the local.properties file comes back as "null"!... I just realized. So probably, all this time, my compiler never managed to get values from local properties, but now all of a sudden, it does!
So I found the android/local.properties file and tried changing the version code there:
sdk.dir=C:\\Users\\karol\\AppData\\Local\\Android\\sdk
flutter.sdk=C:\\src\\flutter
flutter.buildMode=release
flutter.versionName=1.0.0
flutter.versionCode=1 //Change this to 19 (my current version code number)
But that didn't work, because the moment I ran flutter build appbundle, this file changed itself back to the original values...
I then tried adding version code values to my AndroidManifest.xml file, according to serraosays' answer, but that didn't help me either.
Functioning work-around
In the end, I did this in the android/app/build.gradle file:
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
//if (flutterVersionCode == null) {
flutterVersionCode = '19' // TODO: ---Count up with each release
//}
That is, I commented out the condition. Now, my setting would over-write any value retrieved from the local.properties file.
If anyone can tell me the proper way to increment the version code number, I'm all ears! 🙂 But in the meantime, this worked for me, and hopefully for someone else as well.
If you get the above error in the google play console, please change the version: in pubspec.yaml.
Reference. How to set build and version number of Flutter app
and me works
The first step change the version code
The second step go to the other settings and change the bundle version code as well
There are two reasons for this error:
First, is common given in other answers: you must increase the version number to send an update to Play Console. Eg. previous app version: 1.0.5+5 and next update must contain 1.1.2+6. The +6 must be next to the previous update present on your play console.
Second reason for this error is you have skipped some numbers in between. Eg. Previous released version: 1.0.5+5 but the new version you are trying to release is 1.0.6+8. The +8 is not allowed directly, you must put +6 then +7 and then next numbers.
In unreal engine you can change this in project settings. Steps are as follows.
(Me I'm using UE4.27.2)
Step 1:
Open Project Settings
Step 2: Click all settings and in the top search bar type in "version" Without Quotes.
Step 3:
Scroll down to >Platforms>Android>apk packaging
Step 4:
Change the store Version for each +1 what you already have
APK PAckaging
(You do not need to change version display name but you can if you want to this can be edited later on in google console)
change version code here please check the imageenter image description here
Versioning works the other way around. Do not update the pubspec.yaml manually.
See the default comment in the pubspec.yaml:
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
So you should run
flutter build appbundle --build-name 2.0.0 --build-number 2
This updates the pubspec.yaml for you.
For hybrid apps/JavaScript based frameworks like Ionic or Flutter updating package.json is not enough you sometimes, can directly edit build.gradle file in the build folder.
versionCode 2
versionName "2.0"
This is not a good practice

android studio logcat does not show the reason of crashes when i run my app on a real phone

I have a strange problem. when I run my app on Genymotion with android 4.1, everything is good and Logcat works fine and shows everything. but when I run the same app on a real phone(Huawei honour 7 with Android 6), and my app gets crash, logCat does not show the reason for that crash. in the other word, log cat does not show Exceptions. can anyonehelp me?thanks
maybe be useful:
logCat After a crash:
build.gradle(module app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "my.application.id"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
....
}
Best way to fix this to invalidate caches, may it will worked for you.
Go to FILE -> click "INVALIDATE CACHES/RESTART" then a dialog box will pop-up, Select "INVALIDATE CACHES/RESTART" button.
Android studio will automatically restart and rebuild the index.
or,
You can do the following things.
Restart logcat
Change from verbose to debug/error.
The last (Checked the regex ) Change the regex to show selected options only.
or, Look into this Logcat not showing errors from my Huawei P9 phone

Android + Gradle: Best place to set dynamic archivesBaseName

In our Android project we want the filename of our APK to contain information such as the date, git branch name and short commit hash.
We've been setting this as part of our defaultConfig
android {
defaultConfig {
setProperty("archivesBaseName", "$projectName.$branchName.$date.$buildNumber.$versionCode-$versionName-$versionSha")
}
}
This works most of the time but our build sometimes fails with errors pointing to the value being stale (for example after switching branches). Forcing Gradle Sync in Android Studio usually fixes it.
So is there a better, more robust way of making sure that property stays up to date and forces a gradle sync, if necessary?
try to call clean.execute() before
android { ... }
it is the cheapest 'sync' task I can think of :)
clean.execute()
android {
defaultConfig {
setProperty("archivesBaseName", "$projectName.$branchName.$date.$buildNumber.$versionCode-$versionName-$versionSha")
}
}
I was having same issue, they were not always uptodate with the build.
I solved it by using:
project.ext.set("archivesBaseName", "myAppName");
under the defaultConfig block, and I stopped having the problem.
Not sure it will work for the branch, build number or date, but it's worth giving it a shot.
Here's my configs, including the defaultConfig Block. For my case I was only using a hard coded versionName and build Number (I call it versionCode because I set it in the manifest dynamically). But maybe you can tweak it to your needs:
defaultConfig {
minSdkVersion 15
targetSdkVersion 22
versionCode System.getenv("BUILD_NUMBER") as Integer ?: 0
versionName "6.2.5." + versionCode
}
project.ext.set("archivesBaseName", "myAppname" + defaultConfig.versionName);
If an error occurs during the build process, the Messages window appears to describe the issue. Gradle may recommend some command-line options to help you resolve the issue, such as --stacktrace or --debug. To use command-line options with your build process:
Open the Settings or Preferences dialog: On Windows or Linux, select
File > Settings from the main menu.
Navigate to Build, Execution,Deployment > Compiler.
In the text field next to Command-line Options, enter your command-line options.
Click OK to save and exit.
Gradle will apply these command-line options the next time you try building your app.
I have taken the information from this page.

Unable to open debugger port : java.net.SocketException “Socket closed”

I'm using Android Studio, with multiple flavors using Gradle, each with a Debug and Release type, organized as described here, on the bottom half.When I try to start the debugger, I get this error:
Error running androidRecover [installAppDebug]: Unable to open debugger port : java.net.SocketException "Socket closed
I'm also unable to attach the debugger to my device once it's running (it only displays the name of my phone, not the app).
All 3 flavors install on my phone just fine. I just can't get it to let me debug them. I also tested attaching the debugger on a Nexus tablet, and I got the same result.
It's not Gradle specifically as a whole because I can run other Gradle-based apps and attach the debugger just fine so I wonder if it's something with how I've setup my Gradle project and settings.
Here's my build.gradle:
apply plugin: 'android'
apply from: 'signing.gradle'
android {
compileSdkVersion 19
buildToolsVersion '19.0.3'
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile
('proguard-android.txt'), 'proguard-rules.txt'
}
}
productFlavors {
flav1 {
packageName "com.ex.flav1"
versionCode 32
versionName "1.0.5"
signingConfig signingConfigs.flav1
}
flav2 {
packageName "com.ex.flav2"
versionCode 33
versionName "1.0.6"
signingConfig signingConfigs.flav2
}
flav3 {
packageName "com.ex.flav3"
versionCode 27
versionName "1.0.0"
signingConfig signingConfigs.flav3
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:19.+'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/httpmime-4.2.5.jar')
}
I really have no idea what else to try. Android Studio is completely up-to-date. I've restarted Android Studio, my phone, and my computer.
Also, last week I was having this problem, but it was a specific socket that was blocked, from trying to run the emulator and my phone at the same time. I also noticed I had multiple Gradle processes running, because it wasn't killing them on its own, which I often had to kill Android Studio to kill them. Once that was fixed, it was working off and on.
Let me know if you need any other info.
Thanks,
Devin
Edit I finally know why #hasanaydogar's answer works and why it probably would have solved my problem if we had known it then. See my 2nd comment on it to know why, but in short, you have to select in that dropdown the name that matches your app's root directory.
Just Click the button (left side the RUN button).
Select Android. Then Run.
It will connect to your device.
And dont forget to change build variant
I finally understand why I was getting that error so I'm going to explain how I Debug now. Note that I use Gradle (build multiple apk's using the same code), which might influence some how you use the third part of this answer.
For these to work, in the dropdown next to the debug (icon in #1) and run buttons in the top toolbar, you have to have the one selected with the following icon next to it because that's the name of the root directory of your app where all your code lives:
To start debugging from the beginning, I run the app in Debug mode from the start, using this button in your toolbar:
To attach the debugger to the app when it's already running as #scottyab mentioned, I click the Attach Debugger button in your toolbar:
To run the release version of my app in debug mode, I've started changing my strings in the Debug version of strings.xml in the file path myApp/src/appNameDebug(verses appNameRelease)/res/values/strings.xml, more easily seen here, on the bottom half. When I say change, I really mean that I have two versions of all the strings (3 in my case) necessary to change from using the debug server to using the release server. It might not be completely kosher, but it takes about 5 seconds to go the file, and hold down Cmd+/ and uncomment and comment all of the appropriate lines.
My Release version is just there for when I'm ready to build an apk for release.
Doing things in this way has eliminated that error popping up anymore. I think the Release version is just not made for debugging, and I haven't found an easy way to turn the debug flags on when in Release mode.
I managed to get this working by attaching the debugger after a build see Unable to open debugger port : java.net.SocketException "Socket closed"
I managed to get rid of this problem by killing & restart the adb process,hope this would help :]
I have solved this question with reference to the following SO Answer
The "Select Run/Debug Configuration" button in android studio 2.3.2
Change the Debug type to Native

Is there an easy way to have a test version of an app and a release version installed on an android phone?

Say I have a production version com.android.xyz and this is production
then I am developing something and i want to load both this version and the production version on my phone so it's side by side. I know I can create a new package like com.android.abc and then I would have a second app which is basically a clone of com.android.xyz.
Thoughts?
Thanks in advance,
Reid
IF you are using Android Studio with Gradle, there is an easy way to do this. I still keep the the same packageName in AndroidManifest.xml (at least current gradle needs this duplicate definition)
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
package="com.android.xyz">
build.gradle
def devBuildName = "dev"
def testBuildName = "test"
android {
defaultConfig {
versionCode 70
versionName "2.2.3"
minSdkVersion 10
targetSdkVersion 19
packageName "com.android.xyz"
}
buildTypes {
debug {
packageNameSuffix "."+devBuildName
versionNameSuffix "-"+devBuildName.toUpperCase()
}
test.initWith(buildTypes.debug)
test {
packageNameSuffix "."+testBuildName
versionNameSuffix "-"+testBuildName.toUpperCase()
}
}
}
You can look at my full dev/release example at github.
You need to change the package name. IMO the easiest way to do this is by writing a perl/python script to iterate through the files and change the package name based on the build type. Or run a C style macro preprocessor over the files first.

Categories

Resources