当前位置:编程学习 > JAVA >>

使用downloadmanager下载书籍下载完成后不到达BroadcastReceiver的onreceive方法


使用downloadmanager下载书籍下载完成后不到达BroadcastReceiver的onreceive方法
代码如下:
public class Load1Activity extends Activity {
// UI组件
private TextView mTextView;
private EditText mEditText;
private Button mButton;

private DownloadManager dm;
private BroadcastReceiver mReceiver;
private long[] downloadId;
private Handler handler = new Handler();
private String filePath = "",dizhi,item;
private int pauseCount = 0;
public String[] as; 
private String DOWNLOAD_BROATCAST_IDENTIFIER = "android.intent.action.DOWNLOAD_COMPLETE";
String fileName;
String downloadPath;
int tag,i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


// requestWindowFeature(Window.FEATURE_NO_TITLE);// 没有标题
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
setContentView(R.layout.activity_load1);
// DownloadManager Service
i=0;

mEditText = (EditText) findViewById(R.id.dizhi);
tag=0;

dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// 检查下载目录是否存在
//File f = Environment
// .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//filePath = f.getAbsolutePath().toLowerCase() + "/";
filePath="/mnt/sdcard/";
try {
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdir();
}

} catch (Exception e) {
}
if(Dp.biaoshi.equals("1")){

Intent intent=getIntent();
dizhi=intent.getStringExtra("dizhi");
mEditText.setText(""+dizhi);
}
if(Dp.biaoshi.equals("2")){
Intent intent1=getIntent();
item=intent1.getStringExtra("item");
Dp.as=item.split(",");
mEditText.setText("http://192.168.38.110:90/Book/"+Dp.as[0]);
downloadId=new long[Dp.as.length];

// 初始化对象
mTextView = (TextView) findViewById(R.id.textview123);
;
mButton = (Button) findViewById(R.id.xiazai);
mButton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

// 启动thread监控下载速度
handler.postDelayed(mRunnable01, 1000);


//mTextView.setText(downloadPath + "\n网址不正确");

}
}
);
// 给予范例练习的下载文件





}



// Runnable my=new Runnable(){
//
// public void run() {
// for(int i=0;(i<as.length)&&(Dp.percent.equals("100%"));i++){
// mEditText.setText("http://192.168.38.110:90/"+as[i]);
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
//
//
// };
// };
// Thread t1=new Thread(my);
// t1.start();
//





// 按下button后开始下载
// mButton.setOnClickListener(new OnClickListener() {
//
// public void onClick(View v) {
// // TODO Auto-generated method stub
//
// // 启动thread监控下载速度
// handler.postDelayed(mRunnable01, 1000);
//
//
// mTextView.setText(downloadPath + "\n网址不正确");
//
// }
// }
//);

}
// 捕捉Pending与下载进度的Thread
private Runnable mRunnable01 = new Runnable() {

@Override
public void run() {
if(Dp.biaoshi.equals("2")){
mEditText.setText("http://192.168.38.110:90/Book/"+Dp.as[i]);}
// TODO Auto-generated method stub
Log.i("开始监控下载进度", "监控点一");
 
// 检查网址是否正确
//if (URLUtil.isNetworkUrl(downloadPath)) {
// 取得http://远程档名
 for(int x=0;x<Dp.as.length;x++){
 mEditText.setText("http://192.168.38.110:90/Book/"+Dp.as[x]);
 downloadPath = mEditText.getText().toString();
 
 fileName = downloadPath.substring(downloadPath
.lastIndexOf("/") + 1);
// 建立request
Request req = new Request(Uri.parse(downloadPath));
req.setAllowedOverRoaming(false);
req.setVisibleInDownloadsUi(true);
// 设置下载存放位置
req.setDestinationUri(Uri.parse("file://" + filePath
+ fileName));
req.setDescription(filePath);
// 发送请求并取得Download
downloadId[x] = dm.enqueue(req);}
mTextView.setText("开始下载...\n" + downloadPath);
mButton.setEnabled(false);


try {
String tBytes = "";
String dBytes = "";
String percent = "";
String status = "";
// 取得下载信息
Cursor cursor = dm.query(new Query().setFilterById(downloadId));
// 如果一次下载至少1个文件
if (cursor.getCount() > 0) {
//Log.i("开始监控下载进度", "监控点二"+cursor.getCount());
cursor.moveToFirst();
while (!cursor.isAfterLast()) {

status = cursor.getString(cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS));
//Log.i("开始监控下载进度", "监控点三转换"+status);
//Log.i("开始监控下载进度", "监控点四"+status.equalsIgnoreCase(Integer
//.toString(DownloadManager.STATUS_RUNNING)));
if (!status.equalsIgnoreCase(Integer
.toString(DownloadManager.STATUS_RUNNING))) {
//Log.i("开始监控下载进度", "监控点五"+status.equalsIgnoreCase(Integer
// .toString(DownloadManager.STATUS_RUNNING)));
// 下载中则显示下载进度显示
dBytes = cursor
.getString(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

// 取得文件的全部内容Size(byte)
tBytes = cursor
.getString(cursor
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
// 换算成百分比
Dp.percent = Integer.toString((int) ((Double.parseDouble(dBytes) / Double
.parseDouble(tBytes)) * 100))
+ "%";
// if(i<Dp.as.length&&Dp.percent.equals("100%")){
// i++;
// Thread.sleep(10000);
// }
mTextView.setText("下载中..." + Dp.percent);
handler.postDelayed(mRunnable01, 1000);
}

else if (!status.equalsIgnoreCase(Integer
.toString(DownloadManager.STATUS_PAUSED))) {
pauseCount++;
// 下载暂停5次则取消下载
if (pauseCount > 5) {
pauseCount = 0;
// 停止下载
dm.remove(downloadId);
mTextView.setText("尝试下载超过5次,取消下载...");
mButton.setEnabled(true);

} else {
int reason = cursor
.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
if (reason == DownloadManager.PAUSED_WAITING_TO_RETRY) {
mTextView.setText("下载中止...尝试下载"
+ pauseCount + "次\n"
+ "中止原因:PAUSED_WAITING_TO_RETRY"
);
} else if (reason == DownloadManager.PAUSED_WAITING_FOR_NETWORK) {
mTextView.setText("下载中止...尝试下载"
+ pauseCount + "次\n"
+ "中止原因:PAUSED_WAITING_FOR_NETWORK"

);
} else if (reason == DownloadManager.PAUSED_QUEUED_FOR_WIFI) {
mTextView.setText("下载中止...尝试下载"
+ pauseCount + "次\n"
+ "中止原因:PAUSED_QUEUED_FOR_WIFI"

);
} else if (reason == DownloadManager.PAUSED_UNKNOWN) {
mTextView.setText("下载中止...尝试下载"
+ pauseCount + "次\n"
+ "中止原因:PAUSED_UNKNOWN"

);
}

}handler.postDelayed(mRunnable01, 1000);
}

}

// 将Cursor移至下一个下载队列
cursor.moveToNext();
}



}



catch (Exception e) {

e.printStackTrace();
}
//}

}
};
// 自定义mBroadcasstReceiver接收下载完成信息
public class mBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().toString()
.equals(DOWNLOAD_BROATCAST_IDENTIFIER)) {

Log.e("CCCCCCCCCCCCCCCCCCCCCCCCc", "下载完成");
String reason = "";
String status = "";
Cursor cursor = dm.query(new Query().setFilterById(downloadId));
if (cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
reason = cursor.getString(cursor
.getColumnIndex(DownloadManager.COLUMN_REASON));
status = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
cursor.moveToNext();
Log.i("VVVVVVVVVVVVVVVVVVVVVVVVVVVvv", ""+status+reason);

}
}
if (status.equals("16") && reason.equals("1009")) {
mButton.setEnabled(true);
dm.remove(downloadId);
mTextView.setText("ID: " + downloadId + "消下载,文件已存在!");
} else if (status.equals("16") && reason.equals("404")) {
mButton.setEnabled(true);
dm.remove(downloadId);
mTextView.setText("ID: " + downloadId + " 取消下载,找不到文件!");
} else if (status.equals("8")) {
mButton.setEnabled(true);
mTextView.setText("ID: " + downloadId + " 下载完成!");
}
Log.e("AAAAAAAAAAAAAAAAAAAAAAAAaaa", "aaaaaaaaaaaaaa");

handler.removeCallbacks(mRunnable01);
}
}
}

public void exitActivity(int exitMethod){
try{
switch(exitMethod){
case 0:
System.exit(0);
case 1:
android.os.Process.killProcess(android.os.Process.myPid());
break;
case 2:
finish();
break;
}
}catch(Exception e){
e.printStackTrace();
finish();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
//向系统注册Receive接收下载完成信息
IntentFilter mFilter01=new IntentFilter(DOWNLOAD_BROATCAST_IDENTIFIER);
mReceiver=new mBroadcastReceiver();
registerReceiver(mReceiver,mFilter01);
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
//一旦程序失去焦点,停止下载、注销Receive
unregisterReceiver(mReceiver);
handler.removeCallbacks(mRunnable01);
dm.remove(downloadId);
exitActivity(1);
super.onPause();
}
}
补充:Java ,  Eclipse
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,