Android中如何处理没有互联网和丢失的连接?

时间:2013-09-27 12:10:43

标签: java android android-asynctask

我有一个应用程序需要连接到Internet才能执行某些操作,但是当没有可用的Internet时,它将崩溃。我读过,如果没有互联网,我需要使用try catch括号。我试图使用它,你可以在AsyncTask中看到,但它不起作用。我不知道为什么。该应用程序崩溃。如何处理try catch将它放在我的代码中?

如果应用程序在进程正在进行时丢失了Internet连接,那还有什么呢?我怎么想处理这件事所以我的应用程序不会崩溃。非常感谢你。

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();
        }
      }

这是我的logcat:

 java.net.UnknownHostException: Unable to resolve host "globalmall.ca": No address associated with hostname
    at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    at java.net.InetAddress.getAllByName(InetAddress.java:214)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
    at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:287)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    at java.lang.Thread.run(Thread.java:856)
 Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    at libcore.io.Posix.getaddrinfo(Native Method)
    at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
    at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
    ... 18 more
 Caused by: libcore.io.ErrnoException: getaddrinfo failed: ENETUNREACH (Network is unreachable)
    ... 21 more
threadid=13: thread exiting with uncaught exception (group=0x40e582a0)

3 个答案:

答案 0 :(得分:9)

您可以创建method,也可以在某些类中将方法实例化为static

这是一个名为isConnectedToInternet()的方法,用于检查互联网是否已连接。基于连接回调用函数返回布尔值。

摘录:

 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;
}

您可以根据isConnectedToInternet()的返回值来决定是执行AysncTask还是抛出一些弹出窗口。在这里,我已经添加了用户来引入他的Data Settings

像这样:

  if(isConnectedToInternet())
   {
      // Run AsyncTask
    }
   else
   {
      // Here I've been added intent to open up data settings
   Intent intent=new Intent(Settings.ACTION_MAIN);
   ComponentName cName = new ComponentName("com.android.phone","com.android.phone.NetworkSetting");
   intent.setComponent(cName); 
    }

正如你所提到的那样,如果你在两者之间失去联系。您可以根据httpclient的响应检查状态代码,并向用户弹出相关信息。 您可以将这些代码段集成到AysncTask

  DefaultHttpClient httpclient  = new DefaultHttpClient();
  HttpResponse response = null;
  response = httpclient.execute(httpget);
  int code = response.getStatusLine().getStatusCode();

答案 1 :(得分:4)

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;

     }
}

use this class to check internet availability like
if (CheckNetClass.checknetwork(getApplicationContext())) 
{
new GetCounterTask().execute();
} 
else
{   
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();   
}

希望这会有所帮助..

答案 2 :(得分:0)

有趣。您在堆栈中跟踪这些行:

org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)

这意味着违规行是

response = client.execute(post);

这与您提到的行不同。验证堆栈跟踪&amp;它提到的那条线。另外,如果您通过捕获Exception来修复它,请参阅。如果你不这样做,那么你就会遇到更大的问题,因为UnknownHostExceptionIOException的子类,你已经抓住了它。

相关问题