Download files by link (url) Android

2

How can I download a .apk file from my server and open it as soon as it finishes downloading?

I know I have no code showing what I've done or tried, but it's because I'm truly lost and I do not know where to start. I have webservice in php in which I can bring some data from the database by json using HttpUrlConnection if you have any examples how to do this to download a .apk file I appreciate it.

    
asked by anonymous 24.05.2016 / 21:31

1 answer

2

First, you'll need the following permissions on your AndroidManifest :

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

For Internet access, and for you to be able to save (in this case in the Download folder).

To download, we'll use the class DownloadManager .

We request the download, and when ready, the response comes through a BroadcastReceiver . Here is an example:

//BroadcastReceiver que será invocado ao terminar o download
final BroadcastReceiver onComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction() )){
            openFile();
        }
    }
};

DownloadManager downloadManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
  // registramos nosso BroadcastReceiver
  registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
protected void onDestroy() {
    unregisterReceiver(onComplete);
    super.onDestroy();
}
/*
*Abre o arquivo que realizamos o download
*/
private void openFile(){
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(path, "MovieHD.apk");

    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(install);

}

public void iniciarDownload(){
    Uri uri = Uri.parse("http://dndapps.info/app/MovieHD.apk");

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .mkdirs();

    downloadManager.enqueue(new DownloadManager.Request(uri)
                    .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle("Downlodad")
                    .setDescription("Realizando o download.")
                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                            "MovieHD.apk"));
}

.

    
24.05.2016 / 22:54