如何检查在Android上我的网络连接? [英] How to check my internet access on Android?

查看:92
本文介绍了如何检查在Android上我的网络连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真正想要的是,当用户没有连接,我想展示一些对话,他或她有没有关系。

What I really want is, when the user has no connection, I want to show some dialog that he or she has no connection.

我试图把这个在我的MainActivity,但仍然没有工作。

I tried to put this on my MainActivity but still didn't work.

public boolean isOnline() {
 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 return cm.getActiveNetworkInfo().isConnectedOrConnecting();

}

我也用这一个,但它也没工作:

I also used this one but it didn't also work:

public class ConnectionChangeReceiver extends BroadcastReceiver
    {
      @Override
      public void onReceive( Context context, Intent intent )
      {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(     ConnectivityManager.TYPE_MOBILE );
        if ( activeNetInfo != null )
        {
          Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
        }
        if( mobNetInfo != null )
        {
          Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
        }
      }
    }

我说这对我的清单:

I added this on my manifest:

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

谁能告诉我什么,我做错了,我真的AP preciate了很多。在此先感谢!

Can someone tell me what I'm doing wrong, I would really appreciate it a lot. Thanks in advance!

推荐答案

也许这个链接可以帮助你远一点:<一href="http://stackoverflow.com/questions/4846271/broadcastreceiver-to-obtain-servicestate-information/4846452#4846452">Broadcastreceiver获得ServiceState信息

Maybe this link can help you a bit further: Broadcastreceiver to obtain ServiceState information

您可以过去mentined CommunicationManager code。在您的活动,或者更好,如果你需要从更多活动的机会,你也可以声明类的应用Singletin实例作为静态的,如从那里把它叫做<一个href="http://stackoverflow.com/questions/4846271/broadcastreceiver-to-obtain-servicestate-information/4846452#4846452">here

You could past the mentined CommunicationManager code in your activity, or better, if you need access from more activities, you could also declare the class as static in the Application Singletin instance and call it from there as described here

您还需要注册的BroadcastReceiver在你的应用程序清单:

You also need to register the BroadcastReceiver in your application manifest:

<receiver android:enabled="true" android:name="com.project.mobile.controller.comm.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

享受

这篇关于如何检查在Android上我的网络连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆