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"));
}
.