gpt4 book ai didi

Android - if else 语句

转载 作者:行者123 更新时间:2023-11-29 00:13:44 24 4
gpt4 key购买 nike

我正在使用以下 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();
}

问题是当没有互联网连接时,它会显示 toast,但是当我连接到网络时(保持我的应用程序处于打开状态),它会显示相同的 toast。感谢您的帮助。

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

这两行在我的onCreate

最佳答案

你可以试试这段代码

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

只需复制并粘贴此代码并将 ImageView 的 xml 和 id 替换为您的。

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

关于Android - if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28138168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com