1在activity中注册系统的广播
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
package com.yifei.myapplication;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String TAG ="MainActivity12";
private MyService myService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//系统的检测网络的广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
myService = new MyService();
registerReceiver(myService, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myService);
}
}
在广播中监听
package com.yifei.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
public class MyService extends BroadcastReceiver {
public static final String receiver = "com.yifei.myapplication.MyService";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(MainActivity.TAG, "onReceive: MyService");
//获取到系统管理网络的管理者
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Toast.makeText(context, "当前存在网络", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"没有网络",Toast.LENGTH_SHORT).show();
}
}
}
mainifest.xml 网络权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />