0

I've seen a few answers related to this but can't quite seem to find what I'm looking for. Say I have a self hosted app. Now say I've made some changes to that app and would like to let the user know within the app that there is an update available. I can get the app to successfully download the apk file and begin installing it. After the installation is "finished" the app closes out. When I restart the app none of the changes I've made have been applied. So it appears the installation has failed, but there was no apparent crash. However, when I install the apk that was downloaded from the Downloads manager it installs just fine and the changes I have made are applied. Any ideas? Here is the section of code I use to download and install programmatically:

String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "TheApp.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);

String url = "myapplocation";

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading necessary update files.");
request.setTitle("Updating The App");

final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);

BroadcastReceiver onComplete = new BroadcastReceiver() {
    public void onReceive(Context ctxt, Intent intent) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.setDataAndType(uri,
                manager.getMimeTypeForDownloadedFile(downloadId));

                startActivityForResult(install, 0);

                unregisterReceiver(this);
    }
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Cœur
  • 37,241
  • 25
  • 195
  • 267
mac
  • 485
  • 1
  • 6
  • 29
  • You are not telling the download manager where to save the downloaded file. Nor the directory. Nor under which file name. Use setDestinationUri(). – greenapps May 12 '17 at 12:48

1 Answers1

-1

Get VersionName and VersionCode for current Running application. code:

             try {
                        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                        Common.VersionName = pInfo.versionName;
                        Common.VersionCode = pInfo.versionCode;
                        Log.e("VersionCode", ">>>>>>>>>>" + Common.VersionCode + Common.VersionName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
**Check the Version Names**
                if (!Common.VersionName.equals(Common.VersionNamefromWebApi)) {
                        AlertDialogUpdate(MakeTransactionActivity.this, Common.AppUpdateTitle, "YokoYepi Version" + Common.VersionNamefromWebApi + " available.");
                    }
**Alert Dialog Box**    
     public void AlertDialogUpdate(Activity activity, String title, CharSequence message) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setCancelable(false);
            if (title != null) builder.setTitle(title);
            builder.setMessage(message);

            builder.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    new DownloadNewVersion().execute();
                    dialog.dismiss();
                }
            });
            builder.show();
        }    
**Download and Install the .apk file from URL**      
    class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                bar = new ProgressDialog(MakeTransactionActivity.this);
                bar.setCancelable(false);
                bar.setMessage("Downloading...");
                bar.setIndeterminate(true);
                bar.setCanceledOnTouchOutside(false);
                bar.show();
                stoptimertask();
            }

            protected void onProgressUpdate(Integer... progress) {
                super.onProgressUpdate(progress);
                bar.setIndeterminate(false);
                bar.setMax(100);
                bar.setProgress(progress[0]);
                String msg = "";
                if (progress[0] > 99) {
                    msg = "Finishing... ";
                } else {
                    msg = "Downloading... " + progress[0] + "%";
                }
                bar.setMessage(msg);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                startTimer();
                bar.dismiss();
                if (result) {
                    Toast.makeText(getApplicationContext(), "Update Done",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Error: Try Again",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected Boolean doInBackground(String... arg0) {
                Boolean flag = false;
                try {
                    String PATH;
                    Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                    if (isSDPresent) {
                        PATH = Environment.getExternalStorageDirectory() + "/Download/";
                    } else {
                        PATH = Environment.getDataDirectory() + "/Download/";
                    }
                    File file = new File(PATH);
                    file.mkdirs();
                    File outputFile = new File(file, "yokoyepi.apk");
                    if (outputFile.exists()) {
                        outputFile.delete();
                    }
                    // Download File from url
                    URL u = new URL(Common.AppUpdateURL);
                    URLConnection conn = u.openConnection();
                    int contentLength = conn.getContentLength();

                    DataInputStream stream = new DataInputStream(u.openStream());

                    byte[] buffer = new byte[contentLength];
                    stream.readFully(buffer);
                    stream.close();

                    DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
                    fos.write(buffer);
                    fos.flush();
                    fos.close();
                    // Install dowloaded Apk file from Devive----------------
                    OpenNewVersion(PATH);
                    flag = true;
                } catch (MalformedURLException e) {
                    Log.e(TAG, "Update Error: " + e.getMessage());
                    flag = false;
                } catch (IOException e) {
                    Log.e(TAG, "Update Error: " + e.getMessage());
                    flag = false;
                } catch (Exception e) {
                    Log.e(TAG, "Update Error: " + e.getMessage());
                    flag = false;
                }
                return flag;
            }

        }         
     void OpenNewVersion(String location) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(location + "yokoyepi.apk")),
                    "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
// if your not install u should call the function in onResume().
// again it will check whether apk updated or not.
vels
  • 95
  • 1
  • 4