0
在我用的onpause和onstop和ondestroy下面的代碼,但它是無用的,當用戶關閉wifi保存不完整的文件,但我想在用戶關閉wifi時,取消下載。如果關閉wifi,取消下載[android]
我該怎麼辦?
我應該在代碼中添加什麼?
我的代碼:
public class DoaMatn1 extends Activity implements OnClickListener {
// .
// .
// .
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doamatn);
// .
// .
// .
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-tavasol.mp3");
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplaydoa :
// .
// .
// .
case R.id.btndowndoa :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-tavasol.mp3").exists())
downloadTask = (DownloadFileFromURL) new DownloadFileFromURL().execute(file_url);
}}
@Override
protected void onStop() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onStop();
}
@Override
protected void onPause() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onPause();
}
@Override
protected void onDestroy() {
if(downloadTask!=null){
downloadTask.cancel(true);
}
super.onDestroy();
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onCancelled() {
File file= new File("/sdcard/EBKH/basem-tavasol.mp3");
file.delete();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-tavasol.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}
所以你想取消下載時關閉wifi? –
創建一個線程,在經過一段時間後檢查互聯網連接。如果發現沒有互聯網連接,那麼你必須取消你的DownloadFileFromURL AsyncTask。 –