Download files by link(url) Android

Asked

Viewed 3,673 times

2

There’s a way I can download a file .apk from my server and open it as soon as it has finished downloading?

I know I don’t have any code showing what I’ve done or tried, but it’s because I honestly am lost and I don’t know where to start. I have one webservice in php in which I can bring some data from the bank by json using the HttpUrlConnection if you have any example of how to do this to download a file .apk I thank you.

1 answer

3


First, you will need the following permissions in your Androidmanifest:

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

So that there is Internet access, and so that you can save (in this case in the Download folder).

To download, we will use the class Downloadmanager .

We request the download, and when ready, the answer comes through a Broadcastreceiver. Follow 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"));
}

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.