2012-11-28 103 views
2

当没有互联网连接时,我的活动会关闭。如何防止这种情况发生?我正在考虑向用户显示一条消息,表示没有互联网连接,如果它没有连接。在哪些方面我应该更改代码?在此先感谢当没有互联网连接时,活动关闭

public class Myclass extends BaseActivity { 

private String[] imageUrls; 

private DisplayImageOptions options; 

private InputStream is; 

private String result; 

@SuppressLint("NewApi") 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.ac_image_grid); 


    imageUrls = new String[1000]; 

    try{ 

     HttpClient httpclient = new DefaultHttpClient(); 

     HttpPost httppost = new HttpPost(D.url+"gal.php"); 

     List nameValuepairss = new ArrayList(1); 
     // adding attributes to List 
     nameValuepairss.add(new BasicNameValuePair("type","gal_living")); 

     httppost.setEntity(new UrlEncodedFormEntity(nameValuepairss)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
     Log.e("log_tag", "connection success username"); 

}catch(Exception e){ 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
     Toast.makeText(getApplicationContext(), "fail1", Toast.LENGTH_SHORT).show(); 

} 
//convert response to string 
try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 

     } 
     is.close(); 

     result=sb.toString(); 
}catch(Exception e){ 

     Log.e("log_tag", "Error converting result :::"+e.toString()); 
    // Toast.makeText(getApplicationContext(), "fail1", Toast.LENGTH_SHORT).show(); 

} 
try{ 


    JSONArray jArray = new JSONArray(result); 
    int arrayLength=jArray.length(); 
    final String url[]=new String[arrayLength]; 

    for(int i=0;i<arrayLength;i++){ 
      JSONObject json_data = jArray.getJSONObject(i); 



      url[i]=json_data.getString("url"); 
    } 
    List<String> urls = new ArrayList<String>(); 
    urls.addAll(Arrays.asList(url)); 
    imageUrls = urls.toArray(new String[0]); 

} catch(JSONException e){ 
    Log.e("log_tag", "Error parsing data:::::again? "+e.toString()); 
    } options = new DisplayImageOptions.Builder() 
     .showStubImage(R.drawable.stub_image) 
     .showImageForEmptyUri(R.drawable.image_for_empty_url) 
     .cacheInMemory() 
     .cacheOnDisc() 
     .build(); 
    GridView gridView = (GridView) findViewById(R.id.gridview); 
    gridView.setAdapter(new ImageAdapter()); 
    gridView.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      startImageGalleryActivity(position); 
     } 
    }); 
} 

private void startImageGalleryActivity(int position) { 
    Intent intent = new Intent(this, ImagePagerActivity.class); 
    intent.putExtra(Extra.IMAGES, imageUrls); 
    intent.putExtra(Extra.IMAGE_POSITION, position); 
    startActivity(intent); 
} 

public class ImageAdapter extends BaseAdapter { 
    @Override 
    public int getCount() { 
     return imageUrls.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     final ImageView imageView; 
     if (convertView == null) { 
      imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false); 
     } else { 
      imageView = (ImageView) convertView; 
     } 

     imageLoader.displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() { 
      @Override 
      public void onLoadingComplete(Bitmap loadedImage) { 
       Animation anim = AnimationUtils.loadAnimation(LivingGrid.this, R.anim.fade_in); 
       imageView.setAnimation(anim); 
       anim.start(); 
      } 
     }); 

     return imageView; 
    }}} 
+0

你可以粘贴在你的日志? –

+1

在第一个catch块中添加一个返回工作对我来说..这是最容易的.. –

回答

0

访问主线程我想你可以把第一个catch子句中的回报。因为尽管你已经发现了Http Connection异常,但下面的代码仍然会被执行。那时候,“is”是空的,所以从“is”读取会导致崩溃。

try{ 

    HttpClient httpclient = new DefaultHttpClient(); 

    HttpPost httppost = new HttpPost(D.url+"gal.php"); 

    List nameValuepairss = new ArrayList(1); 
    // adding attributes to List 
    nameValuepairss.add(new BasicNameValuePair("type","gal_living")); 

    httppost.setEntity(new UrlEncodedFormEntity(nameValuepairss)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    Log.e("log_tag", "connection success username"); 

}catch(Exception e){ 
    Log.e("log_tag", "Error in http connection "+e.toString()); 
    Toast.makeText(getApplicationContext(), "fail1", Toast.LENGTH_SHORT).show(); 

    return; // ADD return HERE!!!!!!!!!!!! 
} 
+0

谢谢..你不介意给我看如何返回在我的代码中给出? –

+0

我在答案中添加了代码。 – TieDad

+0

谢谢@Evan Li,你的想法对我有用。尽管asynctask很有用,但在我的情况下,你的想法已经足够了。谢谢 –

1
  1. 全部移动互联网相关的代码为AsyncTask。如果你不这样做,这个应用程序将在任何Android 4.0+设备上立即崩溃。
  2. 添加自由错误检查 - 即如果互联网连接失败,请勿尝试从中读取。
  3. 从onCreate中启动AsyncTask,在onPostExecute中或者使用获取结果更新UI,或者在失败时显示消息。
1

试试这个。

这会告诉你,如果你连接到网络:

boolean connected = false; 
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
      connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) { 
     //we are connected to a network 
     connected = true; 
    } 
    else 
     connected = false; 

警告:如果您连接到Wi-Fi网络不包括互联网接入,或者需要基于浏览器的认证,连接将仍然如此。

you will need this permission in your manifest: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

只要使用此功能来检查网络连接是否可用与否:

/** 
    * Checks if the device has Internet connection. 
    * 
    * @return <code>true</code> if the phone is connected to the Internet. 
    */ 
    public static boolean checkNetworkConnection(Context context) 
    { 
     final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

     final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

     if(wifi.isAvailable()||mobile.isAvailable()) 
      return true; 
     else 
      return false; 
    } 
1

使用ConnectivityManager

ConnectivityManager connection = Context.getSystemService(Context.CONNECTIVITY_SERVICE); 

NetworkInfo currentConnection = connection.getActiveNetworkInfo(); 


if(currentConnection != null && currentConnection.isConnected()) 
{ 
    // You have a network connection 
} 
else 
{ 
    // No Network connection 
} 

而且不要忘记

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

额外:

你不应该在主线程内做任何网络操作,否则你会得到ANR(Android Not Responding)对话框。相反,使用AsyncTaskHandler从后台线程

相关问题