在主要活动中创建和注册广播接收器时出现问题

时间:2018-10-27 06:03:15

标签: broadcastreceiver

我的网络支票广播接收器在应用启动时导致延迟。 所以我找到了solution.

  

代替扩展BroadcastReceiver类并创建   NetworkStateChangeReceiver,我在自己的计算机上创建了一个广播接收器   活动并在那里注册。现在可以使用onReceive()方法了   立即被触发。

我已经尝试过这种方法,但是它停止了工作。谁能解决这个问题。

代码如下:

  private BroadcastReceiver mNetworkReceiver;
        static TextView tv_check_connection;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);


            BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    try
                    {
                        if (isOnline(context)) {
                            dialog(true);
                            Log.e("Hi", "Online Connect Intenet ");
                        } else {
                            dialog(false);
                            Log.e("Sorry","Conectivity Failure !!! ");
                            Toast.makeText(MainActivity.context,"No internet",Toast.LENGTH_LONG).show();
                        }
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
            };
            registerNetworkBroadcastForNougat();
});

    public static void dialog(boolean value){...}
    private void registerNetworkBroadcastForNougat() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
            }
        }

        protected void unregisterNetworkChanges() {
            try {
                unregisterReceiver(mNetworkReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }

     protected void onDestroy() {
            super.onDestroy();
            unregisterNetworkChanges();}
    private boolean isOnline(Context context) {
            //try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            //should check null because in airplane mode it will be null
            return (netInfo != null && netInfo.isConnected());
            //} //catch (NullPointerException e) {
            //e.printStackTrace();
            //return false;
            //}
        }

0 个答案:

没有答案