在下面的代码中我使用了onpause和onstop和ondestroy但它没用,当用户关闭wifi时保存不完整的文件但我想在用户关闭wifi时取消下载。
我能做什么?
我应该在代码中添加什么?
我的代码:
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);
}}
答案 0 :(得分:1)
注册广播接收器:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
并收到:
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if (!connected) {
// Stop the download.
}
}
}
此方法将检测到wifi的变化,如果更改是未连接wifi,请取消下载。