Android - if else语句

时间:2015-01-25 15:41:02

标签: android if-statement

我正在使用以下if else语句:

if (isInternetPresent) {
    try {
        startActivity(i2);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
        builder.setTitle("Title");
        builder.setMessage("Message");
        AlertDialog alert = builder.create();
        alert.show();
    }
} else {
    Toast.makeText(getApplicationContext(), "Please check your Internet Connection.", Toast.LENGTH_LONG).show();
}

问题是当没有互联网连接时,它显示吐司,但是当我连接到网络(保持我的应用程序打开)时,它显示相同的吐司。 任何帮助表示赞赏。

    check = new CheckInterNetConnection(getApplicationContext());
    isInternetPresent = check.isConnectingToInternet();

这两行是在我的onCreate

1 个答案:

答案 0 :(得分:2)

你可以尝试这段代码

    public class FirstActivity extends Activity
    {
        ImageView iv;
        boolean isInternetPresent;

        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.yourxml); // containing ImageView

            iv=(ImageView)findViewById(R.id.imageView1);
            iv.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent i2=new Intent(FirstActivity.this,Second.class);

                    isInternetPresent=isNetworkAvailable();

                    if (isInternetPresent) {
                        try {
                            startActivity(i2);
                        } catch (Exception e) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(FirstActivity.this);
                            builder.setTitle("Title");
                            builder.setMessage("Message");
                            AlertDialog alert = builder.create();
                            alert.show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "Please check your Internet Connection.", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

        private boolean isNetworkAvailable() 
        {
            ConnectivityManager connectivityManager 
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
    }

只需复制并通过此代码,然后用您的图像视图替换xml和id。

希望这能以某种方式帮助你。