Android Question Different package name, same app how to uninstall/reinstall?

AscySoft

Active Member
Licensed User
Longtime User
Hi. Recently I had to modify my app package name (from the IDE). After I attach my smartphone and deploy my app, I had two apps that look the same (same icon, same title, same package name - only capital to lowercase) which is confusing (but perfectly normal for android os).
I was wondering if is there a CustomBuildAction or something like that to instruct adb to uninstall old app and re-install the new one after?
 

AscySoft

Active Member
Licensed User
Longtime User
Yes, but in my case this app is already installed on multiple devices. So in order to update correctly I need to somehow uninstall Old.Package.Name app and replace with current old.package.name if you understand...
I know how to install automatically (upgrade) my old app, so i must put a code in there that throw "please unistall first..." but is there a more elegant way?
 
Upvote 0

AscySoft

Active Member
Licensed User
Longtime User
Yes. This is how I did it.
On main Activity_Create, I added the following:
B4X:
If FirstTime Then
    Dim opn As String 'The old package name that must be uninstall if exists
    opn = "b4a.eXample" 'this is Case Sensitive
    If IsThisPackageNameInstalled(opn) = True Then
        Log ("the package name is there. You could proceed to uninstall")
        Msgbox ("Please uninstall first the old version, then restart this app","Uninstall first")
        TryUninstall (opn)
        'If you want at this point you could exit this app after so the user is obliged to uninstall
        Log("Main app will close now, waiting first to uninstall")
        ExitApplication
    Else
    Log ("the package name is not found, probably already uninstalled")
    End If
End If

And the two new subs required:

B4X:
Sub IsThisPackageNameInstalled(OldPackageName As String ) As Boolean
Dim pm As PackageManager
Dim lst As List
lst.Initialize
lst=pm.GetInstalledPackages
Dim str As String
For i=0 To lst.Size -1
    str = lst.Get(i)
    Log (str)
    If str.CompareTo (OldPackageName)=0 Then Return True
Next
Return False
End Sub

Sub TryUninstall(OldPackageName As String )
Dim i As Intent
  i.Initialize("android.intent.action.DELETE", "package:" & OldPackageName)
  StartActivity(i)
End Sub
One question still remain: how to copy private data files saved in internal folder of the old app?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
how to copy private data files saved in internal folder of the old app?
You cannot access internal folders of other apps. You will need to copy the data from the "old app" to the external storage first.

You can update the old app with a new app with the same package name and make it copy the data.
 
Upvote 0

Mark Zraik

Member
Licensed User
Longtime User
I wanted to thank all who where involved with this code!

It went from Checking the Trial Installation date to a Class module I now used in one of my apps. (Still testing it).

I use it to control the installation procedure between a Trial and Paid version of the same app.
I will post it here and attach it as a zip.
I have also played with compiling it to a library and it works great!

When it is fully tested as a library, I'll upload it properly along with the howto's and so forth.
For now, there are comments that show as the Class subs are selected.

Again, thank you B4A Community for all the great ideas, code snippets and support.

NOTE:
how_many_days_Left re-calculated and accurate, added some internal comments
2/20/2015


B4X:
'Class module
Sub Class_Globals
    Dim trialLength_inDays As Int
    Dim thePkg As String
    Dim installedDate As String
    Dim todaysDate As String
    Dim toast As Boolean
    Dim msgbx As Boolean
    Dim extraTxt As String
    Dim trialDIR As String
End Sub

'Initializes the object.
'Example:
'In your activity  - Private tdc As TrialDateChecker
'
'tdc.Initialize("com.pkgname.trial", 15, False, True, "Try the Paid Version!")
'Where the package name is the full package name.
'The length is the time in Days for the trial period. Use -1 to force the uninstall
'Use Toast as Boolean
'Use Messagebox as Boolean
'Extra text for the tag line on the messageboxes and toast. Can also be "".
'-------------------------------------------
'NOTE: If the package you're trying to work with has been Installed, but NEVER been Opened,
'Directory structures are NOT created on the device yet!!
'-------------------------------------------
Public Sub Initialize(pkgName As String, tLength As Int, usetoast As Boolean, usemsgbox As Boolean, extraText As String)
thePkg = pkgName
trialLength_inDays = tLength
todaysDate = DateTime.Date(DateTime.Now)
msgbx = usemsgbox
toast = usetoast
extraTxt = extraText
'check_For_Trial'commented to stop premature uninstall for paid version
End Sub

'checks if the package exists
'returns true or false
'shows messages if initialized as true for toast or messageboxes
'sets the Class Global Variable 'installedDate' to the packages first install date
'Calls to 'IsThisPackageNameInstalled' which uses PackageManager to get the date
'
Sub check_For_Trial As Boolean
If IsThisPackageNameInstalled = True Then
installedDate = DateTime.Date(GetFirstInstallTime)
show_Msg(True)
Return True
Else
show_Msg(False)
Return False
End If

End Sub
'checks if the package is installed
'return true or false
Sub IsThisPackageNameInstalled As Boolean
'Dim OldPackageName As String
Dim pm As PackageManager
Dim lst As List
lst.Initialize
lst=pm.GetInstalledPackages
Dim str As String
For i=0 To lst.Size -1
    str = lst.Get(i)
    If str.CompareTo (thePkg)=0 Then Return True

Next
Return False
End Sub
'Returns the package firstInstallTime As Long, as initialized
'Can be used as standalone
'It first checks that the package exists, returns 0 if it does not!
'
Sub GetFirstInstallTime As Long
If IsThisPackageNameInstalled = True Then
   Dim r As Reflector

   r.Target = r.GetContext
   r.Target = r.RunMethod("getPackageManager")
   r.Target = r.RunMethod3("getPackageInfo", thePkg, "java.lang.String", 0x00000001, "java.lang.int")
   'Log("Getftinstall: " &r.GetField("firstInstallTime"))
   Return r.GetField("firstInstallTime")
   Else
   Return 0
End If 
End Sub
'Shows the Messageboxes or Toast or Both as initialized
'
Sub show_Msg(pkgTrue As Boolean)
Dim days_Left As Int

If pkgTrue = True Then

    days_Left = how_many_Days_Left
      
        
        If days_Left <= trialLength_inDays AND days_Left >= 0 Then
      
            If days_Left = 0 Then
            'Log("1. Days Left:" &days_Left&msgbx)
          
                If msgbx = True Then
                    Msgbox ("This is your LAST Day"&CRLF&"to use this '"&trialLength_inDays&"' Day Trial version."&CRLF&CRLF _
                                &"Date Installed: " &installedDate&CRLF _
                                    &extraTxt,"Thank you")
                End If
                If toast = True Then
                ToastMessageShow("This is your LAST Day"&CRLF&"to use this Trial version."&CRLF&CRLF _
                                &"Date Installed: " &installedDate&CRLF _
                                    &extraTxt, True)
                End If
            Else If days_Left = 1 Then
                    'msgbox or toast
                If msgbx = True Then
                Msgbox ("You have '1' Day Left"&CRLF&"to use this Trial version."&CRLF&CRLF _
                            &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                                &"Date Installed: " &installedDate&CRLF _
                                    &extraTxt,"Thank you")
                End If
                If toast = True Then  
                ToastMessageShow("You have '1' Day Left"&CRLF&"to use this Trial version."&CRLF&CRLF _
                                &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                                    &"Date Installed: " &installedDate&CRLF _
                                        &extraTxt, True)
                End If
            Else
            'msgbox or toast
                If msgbx = True Then
                Msgbox ("You have '"&days_Left&"' Days Left"&CRLF&"to use this Trial version."&CRLF&CRLF _
                &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                    &"Date Installed: " &installedDate&CRLF _
                        &extraTxt,"Thank you")
                End If
                If toast = True Then
                ToastMessageShow("You have '"&days_Left&"' Days Left"&CRLF&"to use this Trial version."&CRLF&CRLF _
                                &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                                    &"Date Installed: " &installedDate&CRLF _
                                        &extraTxt, True)
                End If
            End If
          
        Else
                If msgbx = True Then
                Msgbox ("The Trial period is over," _
                &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                    &"Date Installed: " &installedDate&CRLF _
                        &extraTxt,"Thank you")
                End If
                If toast = True Then
                ToastMessageShow("The Trial period is over," _
                &"Thank You For trying our Software. Todays Date: "&todaysDate&CRLF _
                    &"Date Installed: " &installedDate&CRLF _
                        &extraTxt, True)
                End If
                TryUninstall
               ExitApplication      
        End If
Else

    If msgbx = True Then
    Msgbox ("The Trial Version was not found, probably already uninstalled...Moving Onward..."&CRLF _
        ,"Trial Version Not Found")
    End If
        If toast = True Then
        ToastMessageShow("The Trial Version was not found, probably already uninstalled...Moving Onward..."&CRLF _
            , True)  
        End If
    Log ("The package name is not found, probably already uninstalled.")

End If
End Sub
'Returns how many days are left in the trial period as initialized
'Based on Time TicksPerDay
Sub how_many_Days_Left As Int
        Dim installedDOY As Long
        Dim todaysDOY As Long
        Dim difference_inDays As Long
        Dim howmany_Days_Left As Int

        installedDOY = GetFirstInstallTime
        'Log("Installed DOY : " &installedDOY)
      
        todaysDOY = DateTime.Now 
        'Log("Todays DOY : " &todaysDOY)
      
        difference_inDays = (todaysDOY - installedDOY)/DateTime.TicksPerDay
        'Log("difference: " &difference_inDays)
      
        howmany_Days_Left = trialLength_inDays - difference_inDays
        'Log("How Many Left: " &howmany_Days_Left)
      
Return howmany_Days_Left -1

End Sub
'Used for GetSourceDir as initialized
'returns the "applicationInfo" as an Object or Null if the package doesn't exists
'can be used as a standalone
'
Sub GetActivitiesInfo As Object
If IsThisPackageNameInstalled = True Then
    Try
      Dim r As Reflector
      r.Target = r.GetContext
      r.Target = r.RunMethod("getPackageManager")
      r.Target = r.RunMethod3("getPackageInfo", thePkg, "java.lang.String", 0x00000001, "java.lang.int")
      Return r.GetField("applicationInfo")
    Catch
    Log("GetActivitiesInfo Error: " &LastException.Message)
    End Try
  
End If
Return Null  
End Sub
'Gets the directory where the APK is installed
'Returns the directory of the apk as initialized
'Example:
'tdc.GetSourceDir
'returns - "/data/app/location/your.package.apk" as a string
'Or, it returns Empty "" as string
Sub GetSourceDir As String

    Try
    Dim AppInfo As Object
    AppInfo = GetActivitiesInfo
        Dim r As Reflector
        r.Target = AppInfo
        Return r.GetField("sourceDir") 
    Catch
    Log("GetSource Error: " &LastException.Message)
    End Try
    Return ""      
End Sub
'Uses some directory structure assumptions of internal/external structure, NOT DirRootExternal
'Returns a modified directory structure based on the current processes installed working directory
'Used to retrieve files from the Trial Version working directory.
'Example:
'tdc.GetWorkingDir("external", "com.pkgname.paid", "com.pkgname.trial")
'
Sub GetWorkingDir(InOrExt As String, pkgName1 As String, pkgName2 As String) As String
If InOrExt = "internal" Then
            trialDIR = File.DirInternal
            'Log("Trial B4: " &trialDIR)
            trialDIR = trialDIR.Replace(pkgName1, pkgName2)'if android installs to the same directory structure, then this works
            'Log("Trial After: " &trialDIR)
            'Return trialDIR
            End If
          
If InOrExt = "external" Then
            trialDIR = File.DirDefaultExternal
            'Log("Trial B4: " &trialDIR)
            trialDIR = trialDIR.Replace(pkgName1, pkgName2)'if android installs to the same directory structure, then this works
            'Log("Trial After: " &trialDIR)
            'Return trialDIR
            End If
    Return trialDIR
End Sub

'Used to Uninstall the package as Initialized
'Be careful here!, you don't want to Uninstall the wrong package!
'
'Only Un-comment ... for realtime use!
'
Sub TryUninstall
Log("Call to TryUninstall Sub: for package"&thePkg)
'Dim i As Intent
'  i.Initialize("android.intent.action.DELETE", "package:" & thePkg)
'  StartActivity(i)
End Sub
'Returns true if last year was a leap year, otherwise false
'Used to calculate Trail periods that cross over to a new year
'Based on Day of the Year
Sub was_lastYear_leapYear As Boolean

Dim year_Of_Install As String
    year_Of_Install  = DateTime.GetYear(DateTime.DateParse(installedDate))
    Dim ndate As Int
    ndate = year_Of_Install
    'Log(ndate)
    If DateTime.GetDayOfYear(DateTime.DateParse("12/31/"&ndate)) = 366 Then
    'Log("LY True")
    Return True
    Else
    'Log("LY False")
    Return False
    End If
  
End Sub

I hope this is useful to others...Use as you please!

NOTE: This file has been uploaded as a zip, too.
I changed the days left to a more accurate way of doing it using ticks per day rather than Day of the Year. I left the Leap Year routine just in case someone needed it.

Unless, something else should be added, this should be all. I'm open to suggestions.
Mark Z
 
Last edited:
Upvote 0
Top