问题描述
在我的Android应用我有一个按钮,点击后,打开另一个类,使网络电话。
In my android app I have a button that when clicked, opens another class that makes a network call.
我想按钮被点击时要检查一个数据连接,如果没有我想要显示敬酒消息的连接。
I am trying to check for a data connection when the button is clicked and if there isn't a connection I want to display a toast message.
下面是我的onclick方法,因为它代表: -
Here is my onclick method as it stands:-
public void GoToZone(View v)
{
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Intent myIntent = new Intent(MainActivity.this, CustomizedListViewStudentZone.class);
startActivityForResult(myIntent, 0);
}
else {
Context context = getApplicationContext();
CharSequence text = "There seems to be a connection issue";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
我怎么能检查一个连接时,按钮为pressed,如果有一个连接,然后与上面进行,如果没有则显示一条消息说无连接
How would I be able to check for a connection when the button is pressed and if there is a connection then proceed with the above and if there isn't then display a message saying "No Connection"
我真的实施检查挣扎。
感谢
推荐答案
只需使用它。
从任何地方调用此code就会返回你的网络的当前状态。
Call this code from anywhere it will return you the current state of the Network.
public static boolean isInternetAvailable(Context c)
{
ConnectivityManager connectivityManager
= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED;
}
返回true,如果它是连接,否则为false。就以它的输出任何需要的操作。
return true if it is connected, false otherwise. Take any desired action on its output.
请注意:它是一种静态方法。因此,删除static关键字,如果你只是想从Android Activity类中调用它。
Note: Its a static method. So remove static keyword if you just want to call it from within an Android Activity class.
这篇关于检查按钮点击网络状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!