检查android

时间:2015-04-29 06:10:17

标签: android android-alertdialog android-logcat android-context android-internet

我正在开发一个检查互联网是否可用的应用程序......

我从this获得了帮助。

这是我的连接类:

  public class ChechConnection {

private Context _context;

public ChechConnection(Context context){
    this._context = context;
}

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

我正在使用此代码进行检查: 这是充值活动类的代码

ChechConnection cDetactor;
Boolean isInternetPresent = false;

如果有人点击某个按钮,如果有互联网连接则会显示一些内容。

 cDetactor=new ChechConnection(getApplicationContext());
 isInternetPresent = cDetactor.isConnectingToInternet();


   btn_recharge.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
         if (isInternetPresent){
        Toast.makeText(mContext,"Button Pressed",Toast.LENGTH_LONG).show();
        }
        else
            alert.showAlertDialog(mContext,"Check Connection","Check Your Connection Setting",false);
    }
});

这是我自己的对话管理器:

public class ALertDialogManager {

public void showAlertDialog(final Context context, String title, String message,
        Boolean status) {
    final Dialog alertDialog = new Dialog(new ContextThemeWrapper(context, android.R.style.Theme_Translucent));
    alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    alertDialog.setCancelable(true);
    alertDialog.setContentView(R.layout.dialog);
    alertDialog.setTitle(title);

   Button ok=(Button) alertDialog.findViewById(R.id.btncancel);
   Button cancel=(Button) alertDialog.findViewById(R.id.btnsearch);
   ok.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        Activity activity=(Activity) context;
        activity.finish();
    }
});
   cancel.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        alertDialog.dismiss();
    }
});

    alertDialog.show();
}

}

但是如果有互联网连接,它会给我一个错误。请检查我的logcat值:

04-29 11:26:15.011: E/AndroidRuntime(2177): Process: com.example.lifegoal, PID: 2177
04-29 11:26:15.011: E/AndroidRuntime(2177): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.lifegoal.eshop.helper.ALertDialogManager.showAlertDialog(android.content.Context, java.lang.String, java.lang.String, java.lang.Boolean)' on a null object reference
04-29 11:26:15.011: E/AndroidRuntime(2177):     at com.lifegoal.eshop.Recharge_Activity$1.onClick(Recharge_Activity.java:51)

但如果有互联网连接,它会转到其他部分,并为我提供logcat值

谢谢!

5 个答案:

答案 0 :(得分:1)

使用此方法:

public static boolean isDeviceOnline(Context context) {
        boolean isConnectionAvail = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if(netInfo != null)
            return netInfo.isConnected();
            else 
                return isConnectionAvail;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isConnectionAvail;
    }

答案 1 :(得分:1)

这是非常常见的问题,每次都按照逐行教程进行操作。我想您可能忘记了变量cDetactor的初始化。并且始终遵循编码标准,这样你就可以消除这样的错误。

答案 2 :(得分:0)

ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    boolean connection_check = isConnectingToInternet();
    if (connection_check) {
        newuser.setEnabled(false);
        spinner.setVisibility(View.VISIBLE);
}

    else 
        Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT)
                .show();



public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) 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;
}

我想这个。可以帮到你

答案 3 :(得分:0)

创建一个类 NetworkInformation.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(Login.this)) 
                 {
                    //your code
                 }else{
                     Toast.makeText(Login.this,"No network connection",Toast.LENGTH_LONG).show();
                 }

另外不要忘记在 AndroidManifest.xml中定义以下权限:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 4 :(得分:0)

此方法可以正常工作:

public boolean checkInternetConnection(){
      ConnectivityManager connec = 
              (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);

  // Check for network connections
   if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
        connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

       // if connected with internet


       return true;

   } else if (
     connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
     connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {


       return false;
   }
 return false;

}

不要忘记AndroidManifest.xml。您必须定义权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

编码祝你好运。