How to Download and prompt installation of apk

Hi There

I've been struggling to get my application to update from my private server I cannot get the broadcast receiver to work nor a plain installation script PLEASE I'm going insane Any Help would be deeply appreciated.

my script

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.Site.cc/Folder/app.apk");

            // If required by the server, set the credentials.
            //request.Credentials = CredentialCache.DefaultCredentials;
            //request.IfModifiedSince = DateTime.Parse("01-01-1990");
            try
            {
                using (WebResponse response = request.GetResponse())
                {

                    //DateTime dt = System.IO.File.GetCreationTime(FilePath);        //.GetLastWriteTime(FilePath);
                   // DateTime appDate = DateTime.Parse(response.Headers["Last-Modified"].ToString());

                    try
                    {
                        ad = new AlertDialog.Builder(this).Create();
                        ad.SetTitle("INFO");

                        ad.SetMessage("Get New version");
                        ad.SetButton("NOW", delegate
                        {


                            System.IO.File.Delete("/filepath/app.apk");
                            string url = "http://www.Site.cc/Folder/App.apk";
                            DownloadManager.Request Request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
                            Request.SetDescription("Inspections Application");
                            Request.SetTitle("Download Inspections");
                            // in order for this if to run, you must use the android 3.2 to compile your app
                            if (Build.VERSION.SdkInt >= BuildVersionCodes.HoneycombMr1)
                            {
                                Request.AllowScanningByMediaScanner();
                                Request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                                Request.SetMimeType("application/vnd.android.package-archive");
                                Request.SetVisibleInDownloadsUi(true);

                            }
                            Request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, "Inspections.Inspections-Signed.apk");

                            // get download service and enqueue file
                            DownloadManager manager = (DownloadManager)GetSystemService(Context.DownloadService);
                            manager.Enqueue(Request);


                        });
                        ad.SetButton2("LATER", delegate
                        {
                            return;
                        });
                        //ad.SetButton("Continue",new IDialogInterfaceOnClickListener listner);
                        ad.SetCanceledOnTouchOutside(true);
                        ad.Show();


                    }
                    catch (System.Exception ex)
                    {
                        ad = new AlertDialog.Builder(this).Create();
                        ad.SetTitle("INFO");
                        ad.SetMessage(ex.Message);
                        ad.SetCanceledOnTouchOutside(true);
                        ad.Show();
                    }
                   /* 
                        cL.DownloadFile("http://www.site.cc/folder/app.apk", Path);
                        Intent promptInstall = new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse("/sdcard/Download/Inspections.Inspections-Signed.apk")).SetType("application/vnd.android.package-archive");
                        StartActivity(promptInstall); 
                    */
                    //string lastModified = DateTime.Parse(response.Headers["Last-Modified"].ToString()).ToString();
                }
            }
            catch (WebException wex)
            {

            }

if I could just find a way to start the installation wiz for the app when its finished downloading

Posts

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    Wondering will this be my dead end? please anyone help this is the problem

    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=application/vnd.android.package-archive flg=0x10000000 }

    when I run

    Intent promptInstall = new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse("/sdcard/Download/Inspections.Inspections-Signed.apk")).SetType("application/vnd.android.package-archive");

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    Problem Solved

     private void checkdate()
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.Site.cc/Folder/Inspections.Inspections-Signed.apk");
    
                // If required by the server, set the credentials.
                //request.Credentials = CredentialCache.DefaultCredentials;
                //request.IfModifiedSince = DateTime.Parse("01-01-1990");
                try
                {
                    using (WebResponse response = request.GetResponse())
                    {
    
                        DateTime dt = System.IO.File.GetCreationTime("/sdcard/Download/Inspections.Inspections-Signed.apk"); //.GetLastWriteTime("/sdcard/Dowload/Inspections.Inspections-Signed.apk");
                        DateTime appDate = DateTime.Parse(response.Headers["Last-Modified"].ToString());
                       // DateTime current = DateTime.Now;
    
                        if (appDate > dt)
                        {
                            try
                            {
                                ad = new AlertDialog.Builder(this).Create();
                                ad.SetTitle("INFO");
    
                                ad.SetMessage("Update Found \n \n This might take a while depending on Network");
                                ad.SetButton("NOW", delegate
                                {
                                    try
                                    {
                                        System.IO.File.Delete("/sdcard/download/Inspections.Inspections-Signed.apk");
                                        cL.DownloadFile("http://www.Site.cc/Folder/Inspections.Inspections-Signed.apk", "/sdcard/download/Inspections.Inspections-Signed.apk"); // Download Using HttpWebRequest
    
                                        Intent promptInstall = new Intent(Intent.ActionView).SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/download/" + "Inspections.Inspections-Signed.apk")), "application/vnd.android.package-archive");
                                        //Intent promptInstall = new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse("/sdcard/Download/Inspections.Inspections-Signed.apk")).SetType("application/vnd.android.package-archive");
                                        promptInstall.AddFlags(ActivityFlags.NewTask);
                                        StartActivity(promptInstall);
    
                                    }
                                    catch (ActivityNotFoundException ex)
                                    {
                                        ad = new AlertDialog.Builder(this).Create();
                                        ad.SetTitle("INFO");
                                        ad.SetMessage("Error Installing application Please try again later" + ex);
                                        ad.SetCanceledOnTouchOutside(true);
                                        ad.Show();
                                    }
    
    
                                });
                                ad.SetButton2("LATER", delegate
                                {
                                    return;
                                });
                                ad.SetCanceledOnTouchOutside(true);
                                ad.Show();
    
    
                            }
                            catch (System.Exception ex)
                            {
                                ad = new AlertDialog.Builder(this).Create();
                                ad.SetTitle("INFO");
                                ad.SetMessage(ex.Message);
                                ad.SetCanceledOnTouchOutside(true);
                                ad.Show();
                            }
                        }
                    }
                }
                catch (WebException wex)
               {
    
               }
            }
    
  • Hi A.J !
    did it work for you?
    i wrote this code but it just open the download folder and do not open the package to install! would you please help me?

  • ArnoldBoschArnoldBosch ZAMember ✭✭
    edited February 2014

    Hi There try this one

    public void DownloadFile(string m_uri, string m_filePath)
            {
                var webClient = new WebClient();
    
                webClient.DownloadFileCompleted += (s, e) =>
                {
                    string error = e.Error.Message;
                    //var bytes = e.Result; // get the downloaded data
                    string documentsPath = Android.OS.Environment.ExternalStorageDirectory + "/download/";
                    /************* GetDate ************/
                    DateTime appDate = DateTime.Now;
                    DateTime Jan1St1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    /// <summary>Get extra long current timestamp</summary>
                    long Millis = (long)((appDate - Jan1St1970).TotalMilliseconds);
                    Millis = Millis - 7200000; //current Time
                    long time = DateTime.Now.Ticks;
    
                    /************** Declare Notification Manager *************/
                    this._notificationManager = this.GetSystemService(NotificationService) as NotificationManager;
                    if (this._notificationManager == null)
                    { throw new System.Exception("couldn't get a reference to the notification service"); }
    
                    /************* Set Notification ***************/
                    // Set the icon, scrolling text and timestamp
    
                    Notification notification = new Notification(Resource.Drawable.Icon, "Updates", Millis);
                    notification.Flags = NotificationFlags.AutoCancel;
                    notification.Flags = NotificationFlags.OngoingEvent;
                    //notification.Number = 3;
    
                    Intent promptInstall = new Intent(Intent.ActionView).SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/download/" + "FileName.apk")), "application/vnd.android.package-archive");
                    promptInstall.AddFlags(ActivityFlags.NewTask);
                    // The PendingIntent to launch our activity if the user selects this notification
                    PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, promptInstall, 0);
                    var nBuilder = new Notification.Builder(this);
    
                    // Set the info for the views that show in the notification panel.
                    notification.SetLatestEventInfo(this, "Update Complete", "Click to Install", contentIntent);
    
                    // Send the notification.
                    // We use a layout id because it is a unique number.  We use it later to cancel.
                    // TODO: switch to a unique identifier
                    /************* Send Notification ************/
                    this._notificationManager.Notify(666, notification);
    
                        //System.IO.File.WriteAllBytes(m_filePath, bytes); // writes to local storage  
    
                        //StartActivity(promptInstall);
    
    
    
                };
    
                var url = new System.Uri(m_uri);
    
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                webClient.DownloadFileAsync(url, Android.OS.Environment.ExternalStorageDirectory + "/download/FileName.apk");
    
            }
    

    To show progress if you like

     private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
            {
    
                // Displays the operation identifier, and the transfer progress.
                /*Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
                     (string)e.UserState,
                     e.BytesReceived,
                     e.TotalBytesToReceive,
                     e.ProgressPercentage);*/
    
                int length = Convert.ToInt32(e.TotalBytesToReceive.ToString());
                int prog = Convert.ToInt32(e.BytesReceived.ToString());
                int perc = Convert.ToInt32(e.ProgressPercentage.ToString());
    
    
                Splash.mProgressDialog.Max = length;
                Splash.mProgressDialog.Progress = prog;
            }
    

    And call the method like with

    System.IO.File.Delete(Android.OS.Environment.ExternalStorageDirectory + "/download/FileName.apk");//To Delete old file...
    
     DownloadFile("http://www.link.com/FileName.apk", Android.OS.Environment.ExternalStorageDirectory + "/download/"); // To download new file
    

    Once your download is complete the notification will show then you can click on it to install

    this code does work

    Enjoy

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    Hi Azadeh

    Did this solve your problem?

  • tanx
    i will try it

  • sorry
    i have err in this sections :
    var nBuilder = new Notification.Builder(this);
    Notification do not have a builder
    and

    Splash.mProgressDialog.Max = length;
    Splash.mProgressDialog.Progress = prog;

    what is Splash ?

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    nBuilder you can remove sorry

    and Splash is your Activity name that you can use to show the progress in the current UI or http://developer.android.com/training/notify-user/display-progress.html

  • tanx so much .it works well.
    But if there is any way to start install page automatically? I don't want user click on notification at the top and then installation page open ! I want it start by itself.is there any way?
    thank you in advance

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    okay to just start Installing change your webclient.Download complete to

    webClient.DownloadFileCompleted += (s, e) =>
                {
                    string error = e.Error.Message;
    
                    Intent promptInstall = new Intent(Intent.ActionView).SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/download/" + "FileName.apk")), "application/vnd.android.package-archive");
                    promptInstall.AddFlags(ActivityFlags.NewTask);
    
                        StartActivity(promptInstall);
    
                };
    

    It will show your permissions that the user must just accept and install

    Simple enjoy

  • Hooorrraaaaaaaa!
    thank you so much my friend ! you helped me very much.
    Good luck :)

  • EternalBardEternalBard BRBeta ✭✭

    Thanks for this!

    And for newbies like me, is needed to activate in the project manifest (or properties) the WriteExternalStorage, to succeed to make the download. And IntallPackages.

  • VietNguyenVietNguyen USMember ✭✭
    edited September 2015

    HI Gents,
    My device already install Version 1.0. And i have create new Versoin 2.0. I used the same code as ArnoldBosch's. But when run the download and install function, the error is shown like below. How can i resolve it?

    Android App Not Install. An existing package by the same name with a conflicting signature is already installed

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    Hi VietNguyen

    Sorry Yesterday was a public holiday in South Africa.

    I had such a problem and the conflicting Signature could be caused by the application being built from a different PC.

    Please also confirm that your Version Name and Version Numbers are different.

    Let me know if this is resolved.

  • VietNguyenVietNguyen USMember ✭✭

    Hi Arnold Bosch,
    Exactly, the application being built from a different PC. I resolved it.
    Thank so muck,
    Viet.

  • Vamsi.KatakamVamsi.Katakam USMember ✭✭

    @ArnoldBosch

    How to do this one in ios?
    Please could you help me?

  • TheMaeggesTheMaegges DEMember

    Just call UIApplication.SharedApplication.OpenUrl(new NSUrl("itms-services://?action=download-manifest&amp;url=" + "http://mydomain.com/manifest.plist"));

    You might need to change domain and plist filename depending on your server and manifest name and make sure that the manifest links to a proper ipa file.

  • Eric888Eric888 USMember

    Is possible to use this for xamarin forms?

  • VietNguyenVietNguyen USMember ✭✭

    @ArnoldBosch
    Hi, let me recall this topic. How can I run the installation in the background? I don't want to display Install confirmation box like this.

    Thank you.

  • SteveVSteveV USMember ✭✭

    Unfortunately not possible without rooting the device.

Sign In or Register to comment.