连接检查仅在从Android Studio运行时有效
我的申请有问题。 我设置了一个打开网页的服务来解析某些元素。 因此,在执行任务之前,我需要检查我的internet连接。 这是我的听筒:连接检查仅在从Android Studio运行时有效,android,network-programming,Android,Network Programming,我的申请有问题。 我设置了一个打开网页的服务来解析某些元素。 因此,在执行任务之前,我需要检查我的internet连接。 这是我的听筒: package michele.alertsubito; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class My
package michele.alertsubito;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 8.8.8.8");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public void onReceive(Context context, Intent intent)
{
JsoupAsyncTask task = new JsoupAsyncTask(context);
if (isOnline()){
task.execute();
}
else {
Toast.makeText(context, "alert: no connection!",
Toast.LENGTH_LONG).show();
}
}
}
问题是,此检查仅在我的手机连接到电脑时才开始!
如果我从手机启动我的应用程序(与电脑断开连接),我的isOnline总是返回false,我会得到“无连接”的吐司
有人能帮我吗?您可以使用以下方法检查您的设备是否已连接到Internet:
public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
公共静态布尔值isNetworkAvailable(活动){
ConnectionManager连接=(ConnectionManager)活动
.getSystemService(Context.CONNECTIVITY\u服务);
if(连接性==null){
返回false;
}否则{
NetworkInfo[]info=connectivity.getAllNetworkInfo();
如果(信息!=null){
对于(int i=0;i
您可以使用以下方法检查设备是否连接到interenet:
public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
公共静态布尔值isNetworkAvailable(活动){
ConnectionManager连接=(ConnectionManager)活动
.getSystemService(Context.CONNECTIVITY\u服务);
if(连接性==null){
返回false;
}否则{
NetworkInfo[]info=connectivity.getAllNetworkInfo();
如果(信息!=null){
对于(int i=0;i