在互联网连接打开时打开 Android 应用程序,否则显示无互联网连接消息
open Android app when internet connection is on otherwise display no internet connection message
我刚刚创建了一个 android 应用程序来从网站获取数据。我想检查设备是否有互联网连接。如果设备有互联网连接,运行 我的代码并获取数据并显示它,否则如果设备没有互联网,则显示无互联网连接消息。我试过这段代码来检查互联网连接。如何在有网络连接的情况下调用代码?
我的Java代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
private Context context;
//check Internet connection.
private void checkInternetConnection(){
ConnectivityManager check = (ConnectivityManager) this.context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null)
{
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
@Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//some code
}
//parsing first URL
String [] resultArray=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
String [] resultArray1=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
try{
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
如何运行连接打开时的代码以及应用程序没有互联网连接时如何显示消息?
告诉您如何检查网络连接,然后只需将您的消息放在代码的 "else" 部分
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
创建classNetworkInformation.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkInformation {
private static NetworkInfo networkInfo;
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try{
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
} catch (Exception e) {
e.printStackTrace();
}
// test for connection for WIFI
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// test for connection for Mobile
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
return false;
}
}
现在在像这样调用异步任务之前检查网络是否可用:
if(NetworkInformation.isConnected(YourClassName.this))
{
new FetchWebsiteData().execute();
}else{
Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
}
不要忘记在 AndroidManifest.xml 中包含以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
使用此方法检查网络可用性
public static boolean isNetworkAvailable(Context context) {
try{
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
return s;
}
catch(Exception e){
System.out.println("exception network"+e);
return false;
}
}
如果 returns 为真,您可以继续进行网络呼叫,否则请提示网络不可用消息。
使用下面的代码并制作一个 class 像 NetworkAvailablity.java
public class NetworkAvailablity {
public static boolean checkNetworkStatus(Context context) {
boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
HaveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
HaveConnectedMobile = true;
}
return HaveConnectedWifi || HaveConnectedMobile;
}
}
并在您的代码中使用以下几行,检查互联网是否可用
if (NetworkAvailablity.checkNetworkStatus(getActivity())) {
//code here
}
else
{
// give message here by Toast or create the alert dilog
Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show();
}
//Implement this code in MainActivity and check if isConnectingToInternet(), then allow Otherwise show the No Internet Connection message.
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
检查用户是否连接到 wifi 或任何接入点
最好先检查此方法以查看用户是否有任何连接
如果它 returns 是真的,你可以用下一个方法检查他是否有真正的联系
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
检查用户是否有真实流量通过网络发送请求
注意你不应该在主线程中调用 hasTraffic() 方法(你可以使用 AsyncTask )
public static boolean hasTraffic(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Log.d("check Traffic ", "has traffic");
return true;
} else {
return false;
}
} catch (Exception e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
检查互联网连接
new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPostExecute(Boolean flag) {
if(flag == true){
// do whatever you want
}else{
cantAccessToService();
}
}
@Override
protected Boolean doInBackground(Void... voids) {
if(isOnline(SplashActivity.this) && hasTraffic() ){
return true ;
}else{
return false ;
}
}
}.execute();
试试这个
//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
{
return netInfos.isConnected();
}
}
return false;
}
一旦方法return你必须检查的值
//detect internet and show the data
if(isNetworkStatusAvialable (getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
new FetchWebsiteData().execute();
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}
这里 class 获取有关您的互联网连接的信息
https://gist.github.com/emil2k/5130324
只需复制并粘贴您的代码并使用它的方法
我刚刚创建了一个 android 应用程序来从网站获取数据。我想检查设备是否有互联网连接。如果设备有互联网连接,运行 我的代码并获取数据并显示它,否则如果设备没有互联网,则显示无互联网连接消息。我试过这段代码来检查互联网连接。如何在有网络连接的情况下调用代码?
我的Java代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
private Context context;
//check Internet connection.
private void checkInternetConnection(){
ConnectivityManager check = (ConnectivityManager) this.context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null)
{
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
@Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//some code
}
//parsing first URL
String [] resultArray=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
String [] resultArray1=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
try{
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
如何运行连接打开时的代码以及应用程序没有互联网连接时如何显示消息?
告诉您如何检查网络连接,然后只需将您的消息放在代码的 "else" 部分
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
创建classNetworkInformation.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkInformation {
private static NetworkInfo networkInfo;
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try{
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
} catch (Exception e) {
e.printStackTrace();
}
// test for connection for WIFI
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// test for connection for Mobile
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
return false;
}
}
现在在像这样调用异步任务之前检查网络是否可用:
if(NetworkInformation.isConnected(YourClassName.this))
{
new FetchWebsiteData().execute();
}else{
Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
}
不要忘记在 AndroidManifest.xml 中包含以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
使用此方法检查网络可用性
public static boolean isNetworkAvailable(Context context) {
try{
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
return s;
}
catch(Exception e){
System.out.println("exception network"+e);
return false;
}
}
如果 returns 为真,您可以继续进行网络呼叫,否则请提示网络不可用消息。
使用下面的代码并制作一个 class 像 NetworkAvailablity.java
public class NetworkAvailablity {
public static boolean checkNetworkStatus(Context context) {
boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
HaveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
HaveConnectedMobile = true;
}
return HaveConnectedWifi || HaveConnectedMobile;
}
}
并在您的代码中使用以下几行,检查互联网是否可用
if (NetworkAvailablity.checkNetworkStatus(getActivity())) {
//code here
}
else
{
// give message here by Toast or create the alert dilog
Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show();
}
//Implement this code in MainActivity and check if isConnectingToInternet(), then allow Otherwise show the No Internet Connection message.
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
检查用户是否连接到 wifi 或任何接入点 最好先检查此方法以查看用户是否有任何连接 如果它 returns 是真的,你可以用下一个方法检查他是否有真正的联系
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
检查用户是否有真实流量通过网络发送请求
注意你不应该在主线程中调用 hasTraffic() 方法(你可以使用 AsyncTask )
public static boolean hasTraffic(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Log.d("check Traffic ", "has traffic");
return true;
} else {
return false;
}
} catch (Exception e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
检查互联网连接
new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPostExecute(Boolean flag) {
if(flag == true){
// do whatever you want
}else{
cantAccessToService();
}
}
@Override
protected Boolean doInBackground(Void... voids) {
if(isOnline(SplashActivity.this) && hasTraffic() ){
return true ;
}else{
return false ;
}
}
}.execute();
试试这个
//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
{
return netInfos.isConnected();
}
}
return false;
}
一旦方法return你必须检查的值
//detect internet and show the data
if(isNetworkStatusAvialable (getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
new FetchWebsiteData().execute();
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}
这里 class 获取有关您的互联网连接的信息 https://gist.github.com/emil2k/5130324
只需复制并粘贴您的代码并使用它的方法