廣播時刻監聽網路狀態
阿新 • • 發佈:2019-01-28
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
public class MainActivity extends AppCompatActivity { private MyBroadcaseReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); receiver = new MyBroadcaseReceiver(); this.registerReceiver(receiver, filter); } class MyBroadcaseReceiver extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent) { // 判斷當前傳過來的Action是否是哪裡的斷網Actiion if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context .CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo();//判斷有網路或無網路 if (info != null && info.isConnected()) { //如果有網,判斷當前是否是WIFI或移動資料或者其他第三方網路(VPN等) if (ConnectivityManager.TYPE_WIFI == info.getType()) { Toast.makeText(context, "WIFI已連結,可以下載資料", Toast.LENGTH_SHORT).show(); } else if (ConnectivityManager.TYPE_MOBILE == info.getType()) { Toast.makeText(context, "當前使用的是移動資料,請謹慎使用", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "連結的第三方網路,請謹慎使用", Toast.LENGTH_SHORT).show(); } } else {//如果沒有網路彈出吐司,也可以彈出對話方塊 Toast.makeText(context, "當前沒有網路,請連結網路", Toast.LENGTH_SHORT).show(); } } } } }