Android Question AppUpdating Runtime Permissions problem.

techknight

Well-Known Member
Licensed User
Longtime User
I sat so long on an older SDK that just worked, that I never bothered to tinker around with runtime permissions. Now with Android 14 and the installer blocking the ability of allowing older SDK targeted apps from installing, I have to move forward.

Now I am running into problems, I am using AppUpdating 2.05 and the CheckInstallationRequirements permission always returns false no matter what.

B4X:
'Check whether we already have permission for install other apps.
'If not we open the relevant settings page
'then wait for Activity_Resume and check the value of CanRequestPackageInstalls again
Private Sub CheckInstallationRequirements As ResumableSub
    Dim p As Phone
    If File.ExternalWritable = False Then
       MsgboxAsync("Storage card not available. Make sure that your device is not connected in USB storage mode.", "")
       Return False
    Else If p.SdkVersion >= 26 And updater.CanRequestPackageInstalls = False Then
       MsgboxAsync("In order to receive updates, this application requires permission to install updates to itself. Please allow access.", "")
       Wait For Msgbox_Result(Result As Int)
       Dim in As Intent
       in.Initialize("android.settings.MANAGE_UNKNOWN_APP_SOURCES", "package:" & Application.PackageName)
       StartActivity(in)
       Wait For Activity_Resume '<-- wait for Activity_Resume
       Log(updater.CanRequestPackageInstalls)    'Check the permission (Continues to Return False)
       Return updater.CanRequestPackageInstalls
    Else If updater.CheckNonMarketAppsEnabled = False Then
       MsgboxAsync("Please enable installation of non-market applications." & CRLF & "Under Settings - Security - Unknown sources" _
            & CRLF & "Or Settings - Applications - Unknown sources", "")
       Return False
    Else
       Return True
    End If
End Sub

I inserted a Log in the code above, and it just outputs false. I am running a Samsung Galaxy Tab A7 Lite, and its running the latest OneUI which is still Android 13 based.

It takes me to the unknown sources setting screen like intended, and the permission is turned ON. Turning it off and back on makes no difference.

Hitting the back arrow, brings me back to the app and just outputs a False permission and gives up.

Here is the code that calls the above subroutine:
B4X:
'This subs gets called after each command is executed
Sub update_UpdateComplete
    Log($"UpdateComplete - time: ${DateTime.Time(DateTime.Now)}"$)
    'too lazy to manage error conditions..check apkupdt.ERR_xxx codes if you like
    Select updater.Status
        Case updater.OK_CURVER
'            Log("Running apk version: " & updater.CurVN)
            updater.ReadWebVN
        Case updater.OK_WEBVER
'            Log("Webserver apk version: " & updater.WebVN)
'              Log("Optional Change Log data: " & updater.WebChangeLog)
            If updater.CurVN < updater.WebVN Then
                Msgbox2Async("There is a newer version available. Do you wish to download?" & CRLF & updater.WebChangeLog, "UPDATE FOUND", "Yes", "", "No", Null, False)
                Wait For Msgbox_Result (Result As Int)
                If Result = DialogResponse.POSITIVE Then
                    ProgressDialogHide
                    ProgressDialogShow2("Downloading Update, Please Wait.", False)
                    Wait For (CheckInstallationRequirements) Complete (Result2 As Boolean)
                    Updating = Result2
                    updater.UpdateApk(Result2)
                Else
                    AGsWJWsj 'ContinueBoot
                End If
            Else
                AGsWJWsj 'ContinueBoot
            End If
          Case updater.OK_NEWERAPK
'              Log("Newer version available")
        Case updater.NO_NEWERAPK
'              Log("No newer version available")
            AGsWJWsj 'ContinueBoot
          Case updater.OK_DOWNLOAD
'              Log("Newer version downloaded")
        Case updater.OK_INSTALL
'              Log("User asked to install newer version")
          Case Else
              Log("Status: "&updater.Status)
'            Msgbox("An error occured during the update process, Please try again later.", "Download Error")
            AGsWJWsj 'ContinueBoot
    End Select       
End Sub

I cant use the UDG Example project for testing because it is complaining that starter is declared twice.

Any ideas? thanks!
 

techknight

Well-Known Member
Licensed User
Longtime User
I got the example app to stop complaining by removing the starter service, and the permissions properly work on that one without an error.

The only difference between the example app and my app, is I am calling the runtime permissions request during app startup and before i load any layouts besides my basic splash screen with the code below:

B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        Common.ReadConfig
        updater.Initialize(Me,"update")                   'tab1 has no meaning; use any name you like
     
        StartService("ScoreEngine")
        StartService("CommEngine")     
    End If 
 
    ConfigDB.Initialize(Null)
 
    TmrExpired.Initialize("Expired", 1000)
    TmrExpired.Enabled = False
    RefreshTimer.Initialize("RefreshTimer", 1500)
    RefreshTimer.Enabled = False
    SplashTimer.Initialize("SplashTimer", 2500)
    SplashTimer.Enabled = False 
 
    Updating = False
 
    updater.PackageName = "edge.multisport"
    'this is the complete path to the text file holding the newer version number
    updater.NewVerTxt = "xxxxx"
    'this is the complete path to your newer apk
    updater.NewVerApk = "xxxxx"
         
    updater.setCredentials("xxxx", "xxxx")
 
    khYnbJC8dkjXpP9y'RemoveAllViews
    Wu4gnrUH'GenerateViews
    SplashTimer.Enabled = True 
 
End Sub

Sub SplashTimer_Tick
    SplashTimer.Enabled = False
    If OnLine = True Then
        CheckForUpdates 
    Else
        AGsWJWsj'ContinueBoot 
    End If
End Sub

Sub CheckForUpdates
    Wait For (CheckInstallationRequirements) Complete (Result2 As Boolean)  'This also keeps failing returning false
    ProgressDialogShow2("Checking for Updates", False)
    updater.ReadCurVN
End Sub

'This subs gets called after each command is executed
Sub update_UpdateComplete
    Log($"UpdateComplete - time: ${DateTime.Time(DateTime.Now)}"$)
    'too lazy to manage error conditions..check apkupdt.ERR_xxx codes if you like
    Select updater.Status
        Case updater.OK_CURVER
'            Log("Running apk version: " & updater.CurVN)
            updater.ReadWebVN
        Case updater.OK_WEBVER
'            Log("Webserver apk version: " & updater.WebVN)
'              Log("Optional Change Log data: " & updater.WebChangeLog)
            If updater.CurVN < updater.WebVN Then
                Msgbox2Async("There is a newer version available. Do you wish to download?" & CRLF & updater.WebChangeLog, "UPDATE FOUND", "Yes", "", "No", Null, False)
                Wait For Msgbox_Result (Result As Int)
                If Result = DialogResponse.POSITIVE Then
                    ProgressDialogHide
                    ProgressDialogShow2("Downloading Update, Please Wait.", False)
                    Wait For (CheckInstallationRequirements) Complete (Result2 As Boolean)
                    Updating = Result2
                    updater.UpdateApk(Result2)
                Else
                    AGsWJWsj 'ContinueBoot
                End If
            Else
                AGsWJWsj 'ContinueBoot
            End If
          Case updater.OK_NEWERAPK
'              Log("Newer version available")
        Case updater.NO_NEWERAPK
'              Log("No newer version available")
            AGsWJWsj 'ContinueBoot
          Case updater.OK_DOWNLOAD
'              Log("Newer version downloaded")
        Case updater.OK_INSTALL
'              Log("User asked to install newer version")
          Case Else
              Log("Status: "&updater.Status)
'            Msgbox("An error occured during the update process, Please try again later.", "Download Error")
            AGsWJWsj 'ContinueBoot
    End Select        
End Sub

Also I wanted to clarify this project doesnt have a Starter service either, because it pre-dates before that was a thing.
 
Upvote 0

udg

Expert
Licensed User
Longtime User
Hi, I'm glad to hear you solved it by yourself.
Just yesterday, thanks to your post and another one by Theera, I found that my lib first release was in February 2014.
So, what's better to celebrate its 10th anniversary then a new release (B4xPages + receivers) ?
It will take some time due to other jobs to be completed, so don't hold your breath.. :D

udg
 
Upvote 0

Pesciolina

Active Member
Licensed User
I added the library to a new B4APage project, the installation works correctly, but at the end when the window with the Open button is displayed nothing happens.
However, when I go to open the app I find the updated one.
I also read about this problem in another post, but no one responded.
Where can I intervene?
Thank you
B4X:
AddReceiverText(newinst2,
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>)

' Starting from Android 7 (API 24) we pass a file uri using a FileProvider
AddApplicationText(
  <provider
  android:name="android.support.v4.content.FileProvider"
  android:authorities="$PACKAGE$.provider"
  android:exported="false"
  android:grantUriPermissions="true">
  <meta-data
  android:name="android.support.FILE_PROVIDER_PATHS"
  android:resource="@xml/provider_paths"/>
  </provider>
)

'new external-files-path ensures compatibility with NB6
CreateResource(xml, provider_paths,
<paths>
   <files-path name="name" path="shared" />
   <external-files-path name="name1" path="shared1" />
</paths>
)

AddManifestText(<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="19" />
)
AddPermission(android.permission.REQUEST_INSTALL_PACKAGES)
AddPermission(android.permission.INTERNET)
B4X:
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    'load the layout to Root
    Root.LoadLayout("PageUpdate")
    
    B4XPages.SetTitle(Me, "Update SendTime")
    
    
    
    apkupdt.Initialize(Me,"Update")               'initializes the class
    apkupdt.Verbose = True                    'this one affects the verbosity of the logs
    
    
    
    'ALWAYS NEEDED - this is your app's package name (see "Project/BuilConfigurations/Package")
    apkupdt.PackageName = "B4A....."
    'ALWAYS NEEDED - this is the complete path to the info text file holding the newer version number
    apkupdt.NewVerTxt = "https://www........inf"
    'ALWAYS NEEDED - this is the complete path to your newer apk
    apkupdt.NewVerApk = "https://www........apk"
    'OPTIONAL - Set credentials to access a protected folder. Not needed for this example
    'apkupdt.setCredentials("test","test")
    
    'IndietroIcon = xui.LoadBitmapResize(File.DirAssets, "indietro.png", 32dip, 32dip, True)
    
    
End Sub


Private Sub B4XPage_Appear
    'lblHello.Text = $"Hello ${B4XPages.MainPage.txtUser.Text}!"$
    'UpdateImage
    
    EditText1.Text = ""
    
    apkupdt.ReadCurVN
    apkupdt.ReadWebVN
    
End Sub


Sub btnInstall_Click
    Wait For (CheckInstallationRequirements) Complete (Result As Boolean)
    apkupdt.UpdateApk(Result) 'checks for newer apk, downloads it and asks the user to install it
End Sub


'This subs gets called after each command is executed
Public Sub Update_UpdateComplete
    LogColor($"UpdateComplete - time: ${DateTime.Time(DateTime.Now)}"$, 0xFF556B2F)
    apkupdt.StopSplashScreen
    'too lazy to manage error conditions..check apkupdt.ERR_xxx codes if you like
    Select apkupdt.Status
        Case apkupdt.OK_CURVER
            EditText1.Text=$"${EditText1.Text}Running apk version: ${apkupdt.CurVN}${CRLF}"$
        Case apkupdt.OK_WEBVER
            EditText1.Text=$"${EditText1.Text}Webserver apk version: ${apkupdt.WebVN}${CRLF}"$
            EditText1.Text=$"${EditText1.Text}Optional Change Log data: ${apkupdt.WebChangeLog}${CRLF}"$
            'EditText1.Text=$"${EditText1.Text}Optional FileSize Log data: ${apkupdt.WebFileSize}${CRLF}"$
        Case apkupdt.OK_NEWERAPK
            EditText1.Text=$"${EditText1.Text}Newer version available${CRLF}"$
        Case apkupdt.NO_NEWERAPK
            EditText1.Text=$"${EditText1.Text}No newer version available${CRLF}"$
        Case apkupdt.OK_DOWNLOAD
            EditText1.Text=$"${EditText1.Text}Newer version downloaded${CRLF}"$
        Case apkupdt.OK_INSTALL
            EditText1.Text=$"${EditText1.Text}User asked to install newer version${CRLF}"$
        Case apkupdt.ERR_NOPERM
            Log("No permission to install")
            EditText1.Text=$"${EditText1.Text}User gave no permission to install${CRLF}"$
        Case Else
            EditText1.Text=$"${EditText1.Text}Status: ${apkupdt.Status}${CRLF}"$
    End Select
End Sub

#Region version-safe-apk-installation
'https://www.b4x.com/android/forum/threads/version-safe-apk-installation.87667/

'Check whether we already have permission for install other apps.
'If not we open the relevant settings page
'then wait for Activity_Resume and check the value of CanRequestPackageInstalls again
Private Sub CheckInstallationRequirements As ResumableSub
    If File.ExternalWritable = False Then
        MsgboxAsync("Storage card not available. Make sure that your device is not connected in USB storage mode.", "")
        Return False
    Else If phone.SdkVersion >= 26 And apkupdt.CanRequestPackageInstalls = False Then
        MsgboxAsync("Please allow me to install applications.", "")
        Wait For Msgbox_Result(Result As Int)
        Dim in As Intent
        in.Initialize("android.settings.MANAGE_UNKNOWN_APP_SOURCES", "package:" & Application.PackageName)
        StartActivity(in)
        Wait For Activity_Resume '<-- wait for Activity_Resume
        Return apkupdt.CanRequestPackageInstalls
    Else If apkupdt.CheckNonMarketAppsEnabled = False Then
        MsgboxAsync("Please enable installation of non-market applications." & CRLF & "Under Settings - Security - Unknown sources" _
             & CRLF & "Or Settings - Applications - Unknown sources", "")
        Return False
    Else
        Return True
    End If
End Sub
#End Region
 
Upvote 0

udg

Expert
Licensed User
Longtime User
Hi @Pesciolina , you should have started a new thread (eventually referring to the one where you read about the same problem you encounter).

Anyway, I count on the following weeks to prepare a B4xPages+receivers version of the library.

About your question: as described it looks that the app (the newer version) isn't automatically restarted, failing the last step of the updating procedure. If you have time, try to investigate about the calling to Main in the service. Otherwise, please wait until I have myself sometime to check.
 
Upvote 0

Pesciolina

Active Member
Licensed User
you're right and I apologize.
As information, I didn't tell you that I didn't put the call to the service on the B4XMainPage page but on another page, I hope it can be useful to you.
In the meantime, to the limit of my possibilities, I'll try to look into it
 
  • Like
Reactions: udg
Upvote 0
Top