检查INTENT互联网连接

有一个Android Intent ACTION_XXX在Internet连接可用时通知我? 我将实例化一个BroadcastReceiver ,通知我的应用程序,当用户启用互联网连接(通过WiFi,通过GSM等…)

任何人都可以帮我吗?

 <receiver android:name=".YOURRECEIVER"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

接受的答案是正确的。 我只添加Receiver代码来完成:

 public class NetworkStateReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Log.d("app","Network connectivity change"); if(intent.getExtras()!=null) { NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO); if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) { Log.i("app","Network "+ni.getTypeName()+" connected"); } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) { Log.d("app","There's no network connectivity"); } } } 

更新到@lujop回答:

 public class NetworkStateReceiver extends BroadcastReceiver { private static final String TAG = "NetworkStateReceiver"; @Override public void onReceive(final Context context, final Intent intent) { Log.d(TAG, "Network connectivity change"); if (intent.getExtras() != null) { final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni != null && ni.isConnectedOrConnecting()) { Log.i(TAG, "Network " + ni.getTypeName() + " connected"); } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { Log.d(TAG, "There's no network connectivity"); } } } } 

MyReceiver.java

 public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if(isConnected(context)) Toast.makeText(context, "Connected.", Toast.LENGTH_LONG).show(); else Toast.makeText(context, "Lost connect.", Toast.LENGTH_LONG).show(); } public boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); return isConnected; } } 

AndroidManifest.xml中

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application .............. <receiver android:name="com.example.broadcastreceiversample.MyReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> 

所有答案的缺失部分是提醒注册该行动:

 IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(your_receiver, filter); 

继续喵喵的答案

您可以通过以下方式启用/禁用接收器:

启用

  ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show(); } 

禁用

 ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show(); } 

其中,可以在Intent或onCreate中调用

我使用广播每次检查连接。 创build一个连接信息的类。

 import android.content.Context; import android.content.ContextWrapper; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectivityStatus extends ContextWrapper{ public ConnectivityStatus(Context base) { super(base); } public static boolean isConnected(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo connection = manager.getActiveNetworkInfo(); if (connection != null && connection.isConnectedOrConnecting()){ return true; } return false; } } 

将代码应用到您的活动中:

  private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(!ConnectivityStatus.isConnected(getContext())){ // no connection }else { // connected } } }; 

在您的活动的onCreate()方法中注册广播:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); .. ... .... } 

不要忘记在活动周期中注销/注册:

 @Override protected void onResume() { super.onResume(); your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onPause() { super.onPause(); your_activity_context.unregisterReceiver(receiver); } 

NetworkInfo.isConnected()是testingnetworking状态的不可靠方法,即使没有networking连接(例如没有networking的无线networking),如果有networking连接,它也会返回true。 更可靠的方法是使用CONNECTIVITY_ACTION BroadcastReceiver使用ping

 private void registerInternetReceiver() { if (this.internetReceiver != null) return; this.internetReceiver = new BroadcastReceiver() { @Override public void onReceive (Context context, Intent intent) { if (isInternetAvailable()) Log.i ("Tag", "internet status online"); else Log.i ("Tag", "internet status offline"); } }; IntentFilter filter = new IntentFilter(); filter.addAction (ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver (internetReceiver, filter); } private boolean isInternetAvailable() { try { return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0); } catch (Exception ex) { ex.printStackTrace(); } return false; } 

此代码将工作(在所有版本中),因为清单注册不适用于7+(API 25及以上)设备,请参阅此链接 。

 private void foo(){ registerReceiver(connectionBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } private BroadcastReceiver connectionBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent == null || intent.getExtras() == null) return; ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) { } } } } }; 

我会阅读牛轧糖更新的文档,因为意图已被弃用,由于设备的#,单靠networking信息是不够的。 我会在那里使用连接性pipe理器(连接操作,添加variables)命令和variables,因为去年大部分情况都发生了变化,并且在testing中,启用单元数据始终处于活动状态,详细logging和积极的切换,如果需要的话使用wlanfilter:

https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION