1) 下载管理器
Android下载管理器是在Android 2.3中引入的一项服务,旨在优化长时间运行的下载处理。
下载管理器处理HTTP连接并监视连接更改。在大多数情况下,特别是在下载可能在用户会话之间继续进行的情况下,使用下载管理器是一个好习惯。
应通过传递DOWNLOAD_SERVICE来获取此类的实例,通过getSystemService(String)获得。
通过此API请求下载的应用程序应为ACTION_NOTIFICATION_CLICKED注册广播接收器,以便适当处理用户在通知或下载UI中单击正在运行的下载时的操作。
2) 在前台运行服务
前台服务是指用户主动意识到的服务,因此在内存不足时不会被系统杀死。前台服务必须为状态栏提供通知,并放置在“正在进行”标题下,这意味着除非停止服务或将其从前台移除,否则无法解除通知。
例如,从服务中下载视频应该设置为在前台运行,因为用户明确知道它的操作。状态栏中的通知可能会指示当前的下载进度,并允许用户启动一个活动来与下载过程交互。Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
要将服务从前台移除,请调用stopForeground()方法。该方法接受一个布尔值,指示是否同时删除状态栏通知。该方法不会停止服务。但是,如果您停止了服务
这段代码是用于保存到SD卡中的
package com.Video.ALLTestProject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public class VideoSaveSDCARD extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressBack PB = new ProgressBack();
PB.execute("");
}
class ProgressBack extends AsyncTask < String, String, String > {
ProgressDialog PD;
@Override
protected void onPreExecute() {
PD = ProgressDialog.show(LoginPage.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
@Override
protected void doInBackground(String...arg0) {
DownloadFile("http://beta-vidizmo.com/hilton.mp4", "Sample.mp4");
}
protected void onPostExecute(Boolean result) {
PD.dismiss();
}
}
}
更多信息在此主题中 我如何将视频文件下载到SD卡?