通过广播对实时网络权限的判断

通过广播对实时网络权限的判断

private boolean register = false;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       State wifiState = null;
       State mobileState = null;
       ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
       mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
       if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) {
           // 手机网络连接成功
           new MaterialDialog.Builder(context)
                   .title("网络选择")
                   .content("您当前处于非wifi网络环境下,继续使用可能产生流量")
                   .positiveText("继续")
                   .negativeText("取消")
                   .positiveColor(getResources().getColor(R.color.colorPrimary))
                   .negativeColor(getResources().getColor(R.color.colorPrimary))
                   .onPositive(new MaterialDialog.SingleButtonCallback() {
                       @Override
                       public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                           streamType = "fluxstream";
                           mPresenter.StartRealPlay(m_svPlayer, m_nPort, m_szCameraId, m_pDLLHandle, mTimeOut);
                           mPresenter.startGetStreamRate();
                       }
                   })
                   .show();
       } else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) {
           // 手机没有任何的网络
           UIHelper.showtoast(context, "无网络,请检查网络!");
       } else if (wifiState != null && State.CONNECTED == wifiState) {
           // 无线网络连接成功

       }
   }
};

private void registerNetworkReceiver() {
   if(!register) {
       IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
       this.registerReceiver(mReceiver, filter);
       register = true;
   }
}

private void unRegisterNetworkReceiver() {
   if(register) {
       this.unregisterReceiver(mReceiver);
       register = false;
   }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容