Skip to main content

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone.

Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :-


Before this we have to add these Permissions in Manifest.xml file :

 <uses-permission android:name="android.permission.INTERNET" />  
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  

DownloadNewVersion.java

 class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> {  
     @Override  
     protected void onPreExecute() {  
       super.onPreExecute();  
       bar = new ProgressDialog(getActivity());  
       bar.setCancelable(false);  
       bar.setMessage("Downloading...");  
       bar.setIndeterminate(true);  
       bar.setCanceledOnTouchOutside(false);  
       bar.show();  
     }  
     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) {  
       // TODO Auto-generated method stub  
       super.onPostExecute(result);  
       bar.dismiss();  
       if(result){  
         Toast.makeText(getActivity().getApplicationContext(),"Done!!", Toast.LENGTH_SHORT).show();  
       }else{  
         Toast.makeText(getActivity().getApplicationContext(),"Error: Try Again", Toast.LENGTH_SHORT).show();  
       }  
     }  
     @Override  
     protected Boolean doInBackground(String... arg0) {  
       Boolean flag = false;  
       try {  
         URL url = new URL("http://urlname.com/ApkName.apk");  
         HttpURLConnection c = (HttpURLConnection) url.openConnection();  
         c.setRequestMethod("GET");  
         c.setDoOutput(false);  
         c.connect();  
         String PATH = Environment.getExternalStorageDirectory()+"/Download/";  
         File file = new File(PATH);  
         file.mkdirs();  
         File outputFile = new File(file,"ApkName.apk");  
         if(outputFile.exists()){  
           outputFile.delete();  
         }  
         FileOutputStream fos = new FileOutputStream(outputFile);  
         InputStream is = c.getInputStream();  
         int total_size = 4581692;//size of apk  
         byte[] buffer = new byte[1024];  
         int len1 = 0;  
         int per = 0;  
         int downloaded=0;  
         while ((len1 = is.read(buffer)) != -1) {  
           fos.write(buffer, 0, len1);  
           downloaded +=len1;  
           per = (int) (downloaded * 100 / total_size);  
           publishProgress(per);  
         }  
         fos.close();  
         is.close();  
         OpenNewVersion(PATH);  
         flag = true;  
       } catch (Exception e) {  
         Log.e(TAG, "Update Error: " + e.getMessage());  
         e.printStackTrace();  
         flag = false;  
       }  
       return flag;  
     }  
   }  
   void OpenNewVersion(String location) {  
     Uri uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider",new File(location+"ApkName.apk"));  
     Intent intent = new Intent(Intent.ACTION_VIEW);  
     intent.setDataAndType(uri, "application/vnd.android.package-archive");  
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
     intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);  
     getContext().startActivity(intent);  
   }  

 and finally call this from wherever you want like this:

new DownloadNewVersion ().execute();


It will automatically download apk file from url and install if it finish its downloading task.

That's all you need Thank you for Your time .keep coding and Keep Sharing.

Comments

  1. Connect Play mi arıyorsunuz? Tıklayın: Connect TV Play

    ReplyDelete
  2. Can i do it using Apk Editor ?
    If yes please any video tutorial i really need that please.!

    ReplyDelete
  3. relly niche information about
    apk download

    ReplyDelete
  4. Si buscas una forma cómoda de ver tus programas y películas favoritas, Magis TV para PC es una excelente opción. Su interfaz es sencilla, el contenido se carga rápido y la calidad del streaming es realmente impresionante.

    ReplyDelete
  5. Telegram for PC makes chatting on a computer much easier, especially if you work or study online. It syncs instantly with your phone and offers all the same features in a clean desktop layout. You can download it from here:
    Telegram for PC. It’s a quick and reliable way to stay connected across devices.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to Implement Item Click Interface in Android?

In Android development, creating interactive lists is essential to most apps. Often, these lists include items that users can click on to trigger actions such as opening a new screen or displaying more information. In this tutorial, we’ll walk through how to implement an item click interface in Android using Java and XML. By the end of this guide, you’ll know how to create a RecyclerView with an item click listener that responds to user taps. This approach is widely used in modern Android development because RecyclerView is both flexible and efficient. Step 1: Set Up Your Android Project First, create a new Android project in Android Studio. Make sure to choose Java as the programming language. Step 2: Add Dependencies Make sure that you have the required dependencies for RecyclerView in your build.gradle file. If not, add them like this: dependencies {     implementation 'androidx.recyclerview:recyclerview:1.2.1' } Sync the project after adding the dependency. Step 3: Define ...

Working with Android 11 (Changes and Security Features)

 Hello everyone , I am here with new article which is hot topic nowadays "Android 11" .The stable version of Android.  Android 11 is the eleventh major release and 18th version of Android, the mobile operating system developed by the Open Handset Alliance led by Google. It was released on September 8, 2020.It is comes with many security features and other features as well . And it is now compulsory in play store  to upload new apps with API lavel 30 which is compatible with Android 11 and from November onwards old apps also have to update with API 30 .Some other guidelines you can check out from here . Play Store Guidelines So its clear that we have to update our apps with API level 30 .But Android 11 comes with some changes as well which we have to do in our projects. For example from Android developer site "Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. ". Scoped storage enforcement: Apps...