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.
I do in a common Activity even?
– GabrielLocalhost