botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText campoUrl = (EditText) findViewById(R.id.formulario_URL);
String url = campoUrl.getText().toString();
if (url != null && !url.isEmpty() && verificaConexao() ) {
DownloadManager downloadManager =
(DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
long downloadId = downloadManager.enqueue(request);
DownloadApplication app = (DownloadApplication) getApplication();
app.downloadsAtivos.add(downloadId);
}else if (!verificaConexao()){
Toast.makeText(FormularioMidiaActivity.this, "Não foi possivel fazer download, sem conexão no momento.", Toast.LENGTH_LONG).show();
}
}
});
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
long downloadId = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
DownloadApplication app =
(DownloadApplication) context.getApplicationContext();
if (app.downloadsAtivos.indexOf(downloadId) != -1) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
DownloadManager downloadManager =
(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
String uri =
cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String mime =
cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
Intent abreArquivoIntent = new Intent(Intent.ACTION_VIEW);
abreArquivoIntent.setDataAndType(Uri.parse(uri), mime);
PackageManager packageManager = context.getPackageManager();
if (packageManager.resolveActivity(abreArquivoIntent, 0) != null) {
PendingIntent acaoPendente =
PendingIntent.getActivity(context, 0,
abreArquivoIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notificacao = new NotificationCompat.Builder(context)
.setContentTitle("Download concluído!")
.setContentText(uri)
.setSmallIcon(android.R.drawable.ic_menu_slideshow)
.setAutoCancel(true)
.setContentIntent(acaoPendente)
.build();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(123, notificacao);
Toast.makeText(context,
"Download concluído", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,
"Não tem aplicativo para abrir o download", Toast.LENGTH_SHORT).show();
}
}
cursor.close();
app.downloadsAtivos.remove(downloadId);
}
}
}