Java 在Android中如何处理没有互联网和失去连接的情况?

Java 在Android中如何处理没有互联网和失去连接的情况?,java,android,android-asynctask,Java,Android,Android Asynctask,我有一个应用程序需要连接到Internet以执行某些操作,但当没有可用的Internet时,它将崩溃。我读到我需要使用try-catch括号,以防没有互联网。正如您在AsyncTask中看到的那样,我尝试使用它,但它不起作用。我不知道为什么。应用程序崩溃了。如何处理try-catch在代码中的位置 还有一件事,如果应用程序在处理过程中失去了互联网连接,该怎么办。我该如何处理这件事,这样我的应用程序就不会崩溃。多谢各位 protected void onCreate(Bundle savedIns

我有一个应用程序需要连接到Internet以执行某些操作,但当没有可用的Internet时,它将崩溃。我读到我需要使用try-catch括号,以防没有互联网。正如您在AsyncTask中看到的那样,我尝试使用它,但它不起作用。我不知道为什么。应用程序崩溃了。如何处理try-catch在代码中的位置

还有一件事,如果应用程序在处理过程中失去了互联网连接,该怎么办。我该如何处理这件事,这样我的应用程序就不会崩溃。多谢各位

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.home);
  lv = (ListView) findViewById(R.id.mybookslistview);

  new connectToServer().execute();
}


class connectToServer extends AsyncTask<Void, Void, Void>{
  CustomListViewAdapter adapter;
  HttpResponse response;
  @Override
    protected Void doInBackground(Void... params) {
      ids_list.clear();
      names_list.clear();
      writers_list.clear();

      HttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost(link);
      ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair(word, connectionPurpose));
      try {
        post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        response = client.execute(post);
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        sb = new StringBuffer();
        String tempVar = "";
        while((tempVar = br.readLine()) != null){
          sb.append(tempVar);
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      //Get data from stringbuffer and put it in array list
      if(!sb.toString().trim().contentEquals("null")){
        content_array = sb.toString().split(",");
        for(int s = 0; s < content_array.length; s++){
          if(content_array[s].contains("-")){
            String temp[] = content_array[s].split("-");
            ids_list.add(temp[0].trim());
            names_list.add(temp[1].trim());
            writers_list.add(temp[2].trim());
          }
        }
      }
      return null;
    }

  @Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);

      connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
      mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

      if(!mWifi.isConnected()){
        adb = new AlertDialog.Builder(Home.this);
        adb.setMessage("لا يوجد إنترنت. قم بتفعيل الإنترنت ثم حاول مرة أخرى.");
        adb.setPositiveButton("حاول مجددا", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
            new connectToServer().execute();
            }
            });
        adb.setNegativeButton("إغلاق التطبيق", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            finish();
            }
            });
        //It shows dialog if no connection
        adb.create().show();
      }else{
        list = new ArrayList<Home.ListViewItem>();
        for(x = 0; x < ids_list.size(); x++){
          list.add(new ListViewItem(){{bookName = names_list.get(x); writerName = writers_list.get(x);}});
        }
        adapter = new CustomListViewAdapter(Home.this, list);
        lv.setAdapter(adapter);
        if(sb.toString().trim().contentEquals("null")){
          Toast.makeText(Home.this, "لا توجد نتائج.", Toast.LENGTH_LONG).show();
        }
      }

有趣。堆栈中有以下行的跟踪:

org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
这意味着冒犯的界线是

response = client.execute(post);

这与你提到的那条线不同。验证堆栈跟踪&它提到的行。另外,请查看是否通过捕获
异常来修复它。如果您不这样做,那么您就有一个更大的问题,因为
UnknownHostException
IOException
的一个子类,您已经捕获了它。

您可以创建
方法
,或者在某个类中可以将方法实例化为
静态

这里有一个名为
isconnectedpointernet()
的方法,用于检查internet是否已连接。基于返回调用函数的连接返回布尔值

片段:

 public boolean isConnectedToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          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;
}

正如你提到的,如果你在两者之间失去了联系会怎么样。您可以根据httpclient的回复查看状态码,并弹出相关信息给用户。 您可以在
AysncTask
下集成这些代码段

  DefaultHttpClient httpclient  = new DefaultHttpClient();
  HttpResponse response = null;
  response = httpclient.execute(httpget);
  int code = response.getStatusLine().getStatusCode();
使用此类检查internet可用性,如:

if (CheckNetClass.checknetwork(getApplicationContext())) 
{
new GetCounterTask().execute();
} 
else
{   
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();   
}

希望这有帮助

因此,根据logcat,您可以指出源代码中的哪一行是第106行吗?@TassosBassoukos Appending StringBuffer.while((tempVar=br.readLine())!=null){sb.append(tempVar);}UnknownHostException未被捕获。@MansourFahad如果您没有Internet连接,主机名无法解析,因此,
UnknownHostException
将在try-catch块中捕获
UnknownHostException
,然后,您可以向用户显示一条消息,说明Internet连接不可用这似乎是一个很好的解决方案,但如果连接断开怎么办?@MansourFahad:我在评论中为您的OP添加了一段代码。对于连接断开,请使用此筛选器的BroadcastReceiver:android.net.conn.CONNECTIVITY\u change,我正在尝试相同的解决方案,但因为它已失效我认为最好的解决方案是抛出一个自定义异常,通过在viewmodel中处理它,当连接丢失时将显示错误消息或任何需要的操作
  DefaultHttpClient httpclient  = new DefaultHttpClient();
  HttpResponse response = null;
  response = httpclient.execute(httpget);
  int code = response.getStatusLine().getStatusCode();
public class CheckNetClass {

    public static Boolean checknetwork(Context mContext) {

        NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE))
                           .getActiveNetworkInfo();
        if (info == null || !info.isConnected()) {
            return false;
        }
        if (info.isRoaming()) {
            // here is the roaming option, you can change it if you want to
            // disable internet while roaming, just return false
            return true;
        }

        return true;

    }
}
if (CheckNetClass.checknetwork(getApplicationContext())) 
{
new GetCounterTask().execute();
} 
else
{   
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();   
}