Android:在下载数据时处理意外的互联网断开 [英] Android: handle unexpected internet disconnect while downloading data

查看:112
本文介绍了Android:在下载数据时处理意外的互联网断开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个将数据从远程服务器下载到文件的功能。我仍然对我的代码没有信心。我的问题是,如果在读取流并将数据保存到文件中,突然间我在互联网中断开连接,那么下面的异常情况是否可以捕获到这种事件呢?如果没有,你可以建议如何处理这种事件?



注意:我在一个线程中调用这个函数,以便UI不会被阻止。 p>

  public static boolean getFromRemote(String link,String fileName,Context context){
boolean dataReceived = false;
ConnectivityManager connec =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

if(connec.getNetworkInfo(0).isConnected()|| connec.getNetworkInfo(1).isConnected()){
try {
HttpClient httpClient = new DefaultHttpClient );
HttpGet httpGet = new HttpGet(link);
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params,30000);
HttpConnectionParams.setSoTimeout(params,30000);
HttpResponse响应;
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine()。getStatusCode();
if(statusCode == 200){
HttpEntity entity = response.getEntity();



InputStream in = null;
OutputStream output = null;

尝试{
in = entity.getContent();

String secondLevelCacheDir = context.getCacheDir()+ fileName;

文件imageFile = new File(secondLevelCacheDir);

output = new FileOutputStream(imageFile);
IOUtilities.copy(in,output);
output.flush();
} catch(IOException e){
Log.e(SAVING,无法加载xml,e);
} finally {
IOUtilities.closeStream(in);
IOUtilities.closeStream(output);
dataReceived = true;

}
}
} catch(SocketTimeoutException e){
//处理未连接到客户端!
Log.d(SocketTimeoutException Thrown,e.toString());
dataReceived = false;

} catch(ClientProtocolException e){
//处理未连接到客户端!
Log.d(ClientProtocolException Thrown,e.toString());
dataReceived = false;

} catch(MalformedURLException e){
// TODO自动生成的catch块
e.printStackTrace();
dataReceived = false;
Log.d(MalformedURLException Thrown,e.toString());
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
dataReceived = false;
Log.d(IOException Thrown,e.toString());
}
}
return dataReceived;

}


解决方案

在开始网络通信之前检查网络是否可用的以下代码片段(预防胜于治疗?)。一旦通信开始,我只能希望网络保持可用。如果没有,我将捕获异常并向用户显示一条消息。

  public boolean isNetworkAvailable(){
Context context = getApplicationContext();
ConnectivityManager连接=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity == null){
boitealerte(this.getString(R.string.alert),getSystemService rend null);
} else {
NetworkInfo [] info = connectivity.getAllNetworkInfo();
if(info!= null){
for(int i = 0; i< info.length; i ++){
if(info [i] .getState()== NetworkInfo .State.CONNECTED){
return true;
}
}
}
}
return false;
}

您可以附加任何线程的DefaultThreadHandler,如果有任何异常,将使用



  //使用静态函数附加一个线程的处理程序
Thread.setDefaultUncaughtExceptionHandler(handler);

//创建一个处理程序
private Thread.UncaughtExceptionHandler handler =
new Thread.UncaughtExceptionHandler(){
public void uncaughtException(Thread thread,Throwable ex){
Log.e(TAG,未捕获的例外,ex);
showDialog(ex);
}
};

void showDialog(Throwable t){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder
.setTitle(Exception)
.setMessage(t.toString())
.setPositiveButton(Okay,null)
.show() ;
}


I have here a function that downloads data from a remote server to file. I am still not confident with my code. My question is, what if while reading the stream and saving the data to a file and suddenly I was disconnected in the internet, will these catch exceptions below can really catch that kind of incident? If not, can you suggest how to handle this kind of incident?

Note: I call this function in a thread so that the UI won't be blocked.

public static boolean getFromRemote(String link, String fileName, Context context){ 
        boolean dataReceived = false;
        ConnectivityManager connec =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connec.getNetworkInfo(0).isConnected() || connec.getNetworkInfo(1).isConnected()){
                try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(link);
                        HttpParams params = httpClient.getParams();
                        HttpConnectionParams.setConnectionTimeout(params, 30000);
                        HttpConnectionParams.setSoTimeout(params, 30000);
                        HttpResponse response;
                        response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200){
                            HttpEntity entity = response.getEntity();



                            InputStream in = null;
                            OutputStream output = null;

                            try{
                                in = entity.getContent();

                                String secondLevelCacheDir = context.getCacheDir() + fileName;

                                File imageFile = new File(secondLevelCacheDir);

                                output= new FileOutputStream(imageFile);
                                IOUtilities.copy(in, output);
                                output.flush();
                            } catch (IOException e) {
                                Log.e("SAVING", "Could not load xml", e);
                            } finally {
                                IOUtilities.closeStream(in);
                                IOUtilities.closeStream(output);
                                dataReceived = true;

                            }
                        }
                    }catch (SocketTimeoutException e){  
                        //Handle not connecting to client !!!!
                        Log.d("SocketTimeoutException Thrown", e.toString());
                        dataReceived = false;

                    } catch (ClientProtocolException e) {
                        //Handle not connecting to client !!!!
                        Log.d("ClientProtocolException Thrown", e.toString());
                        dataReceived = false;

                    }catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("MalformedURLException Thrown", e.toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("IOException Thrown", e.toString());
                    } 
                }
            return dataReceived;

        }

解决方案

I use the following snippet to check if Network is Available before I start a network communication(Prevention better than cure?). Once the communication starts, I can only hope that the network remains available throughout. If not, I would catch Exception thrown and display a message to the user.

public boolean isNetworkAvailable() {
   Context context = getApplicationContext();
   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity == null) {
      boitealerte(this.getString(R.string.alert),"getSystemService rend null");
   } else {
      NetworkInfo[] info = connectivity.getAllNetworkInfo();
      if (info != null) {
         for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
               return true;
            }
         }
      }
   }
   return false;
}

You can attach a DefaultThreadHandler with any thread which would be used if any exception go uncaught in the exception-raising code.

[EDIT: Adding sample code]

//attaching a Handler with a thread using the static function
Thread.setDefaultUncaughtExceptionHandler(handler);

//creating a Handler
private Thread.UncaughtExceptionHandler handler=
        new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "Uncaught exception", ex);
            showDialog(ex);
        }
    };

void showDialog(Throwable t) {
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
            builder
                .setTitle("Exception")
                .setMessage(t.toString())
                .setPositiveButton("Okay", null)
                .show();
    }

这篇关于Android:在下载数据时处理意外的互联网断开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆