2013-09-27 74 views
13

我有一個應用程序需要連接到互聯網來執行一些操作,但是當沒有互聯網可用時它會崩潰。我讀過我需要使用try catch支架以防萬一互聯網。我試圖使用它,就像你在AsyncTask中看到的那樣,但它不起作用。我不知道爲什麼。該應用程序崩潰。如何處理嘗試把它放在我的代碼中?如何處理沒有互聯網和失去連接在Android?

還有一件事情,如果應用程序在進程正在進行時丟失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) 
+0

因此,基於該logcat的,你能說明什麼是線在源線#106? –

+0

@TassosBassoukos附加StringBuffer。 \t \t \t \t而((TempVar的= br.readLine())!= NULL){ \t \t \t \t \t \t某人。append(tempVar);} –

+0

UnknownHostException沒有趕上。 – Reinherd

回答

6

您可以創建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(); 
+0

這似乎是一個很好的解決方案,但如果連接丟失怎麼辦? –

+0

@MansourFahad:我在評論中添加了針對您的OP的片段。 –

+0

對於連接丟失使用此篩選器的BroadcastReceiver:android.net.conn.CONNECTIVITY_CHANGE –

0

有趣。您的堆棧跟蹤這些行:

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

這意味着違規行爲

response = client.execute(post); 

這是你提到的線不同。驗證它提到的堆棧跟蹤&。此外,請參閱如果您通過捕獲Exception來修復它。如果你不這樣做,那麼你有更大的問題,因爲UnknownHostException是你已經捕獲的IOException的一個子類。

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

希望這有助於..

相關問題