如何检查在Android上我的网络连接?我的、网络、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. 我试图把这个...

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

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!

推荐答案

也许这个链接可以帮助你远一点:Broadcastreceiver获得ServiceState信息

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

您可以过去mentined CommunicationManager code。在您的活动,或者更好,如果你需要从更多活动的机会,你也可以声明类的应用Singletin实例作为静态的,如从那里把它叫做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>

享受

阅读全文

相关推荐

最新文章