2017-08-01 70 views
0

Android AsyncTask處理,發現沒有互聯網連接系統發出警告「用戶請連接互聯網」。我如何在我的代碼中執行此操作?Android時AsyncTask如果沒有互聯網發現過程如何給出警告「請連接互聯網」

另一個問題是,當互聯網沒有連接其顯示加載,但我不回頁面。如何解決這個問題呢?

我不明白如何在此代碼中執行此操作。

public class data extends AppCompatActivity { 

    private String TAG = MainActivity.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 

    // URL to get contacts JSON 
    private static String url = "http://orangehostbd.com/app/bpl2/index.php"; 

    ArrayList<HashMap<String, String>> contactList; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_data); 

     contactList = new ArrayList<>(); 

     lv = (ListView) findViewById(R.id.list); 

     new GetContacts().execute(); 
    } 

    /** 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(data.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 



     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url); 

      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        JSONArray contacts = jsonObj.getJSONArray("contacts"); 

        // looping through All Contacts 
        for (int i = 0; i < contacts.length(); i++) { 
         JSONObject c = contacts.getJSONObject(i); 

         String id = c.getString("id"); 
         String name = c.getString("name"); 
         String email = c.getString("email"); 
         String address = c.getString("address"); 
         String gender = c.getString("gender"); 

         // Phone node is JSON Object 
         JSONObject phone = c.getJSONObject("phone"); 
         String mobile = phone.getString("mobile"); 
         String home = phone.getString("home"); 
         String office = phone.getString("office"); 

         // tmp hash map for single contact 
         HashMap<String, String> contact = new HashMap<>(); 

         // adding each child node to HashMap key => value 
         contact.put("id", id); 
         contact.put("name", name); 
         contact.put("email", email); 
         contact.put("mobile", mobile); 

         // adding contact to contact list 
         contactList.add(contact); 
        } 
       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        data.this, contactList, 
        R.layout.list_item, new String[]{"name", "email", 
        "mobile"}, new int[]{R.id.name, 
        R.id.email, R.id.mobile}); 

      lv.setAdapter(adapter); 
     } 

    } 
} 

回答

0
  1. 創建Helper類。 在這個類中,創建一個方法來檢查Internet連接。

    public static boolean isNetworkConnected(Context context) { 
        final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); 
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected(); 
    } 
    
  2. 內,您的活動類,使用上面的doInBackgroundisNetworkConnected()方法。

    if (Helper.isNetworkConnected(this)) { 
        // do your stuff 
    } else{ 
        Toast.makeText(YourActivity.this, "Your internet connection is lost.", Toast.LENGTH_SHORT).show(); 
    } 
    
  3. Manifest文件中使用此權限。

    <uses-permission android:name="android.permission.INTERNET" /> 
    
+2

''在doiBackground(...)內的'Toast.makeText(...)'不允許在gui-thread之外 – k3b

0

如果問題是「如何顯示內部doInBackground警告」,因爲你不能訪問GUI內doInBackground技術上可以使用progress indicator of asynctask到郵件傳輸到GUI。

但是我會recommond一個differen形式給出:啓動異步任務

  • 要麼

    描述返回錯誤。