1

请帮助解决问题。任务:创建一个网络监听器。当 Internet 丢失时,显示 ProgressDialog。

ProgressDialog dialog;
private IntentFilter mNetworkStateChangedFilter;
private BroadcastReceiver mNetworkStateIntentReceiver;


@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mNetworkStateChangedFilter = new IntentFilter();
        mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

        mNetworkStateIntentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {



            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                mTypeName = info.getTypeName();
                mSubtypeName = info.getSubtypeName();
                mAvailable = info.isAvailable();

                Log.i(LOGTAG, "Network Type: " + mTypeName 
                    + ", subtype: " + mSubtypeName
                    + ", available: " + mAvailable + " isConnected: " + info.isConnected());
                if (!info.isConnected()){
                    try{
                    showDialog();
                    }catch (Exception e){

                    }

                    }
                else if (info.isConnected()){
                        dismissDialog();    
                }

            }
            }
        };

        setContentView(R.layout.activity_main);
    }

检查模拟器。我进入设置(操作OnPause),拔掉互联网,我回去(onResume) - 创建一个对话,没关系。再次在设置中,打开互联网,对话仍然存在。

@Override
    protected void onPause() {
        Log.d(LOGTAG, "onPause");
        super.onPause();
        unregisterReceiver(mNetworkStateIntentReceiver);
    };
    @Override
    protected void onResume() { 
        Log.d(LOGTAG, "onResume");
        super.onResume();
        registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter);
        unregisterReceiver(mNetworkStateIntentReceiver);
        registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter);
    };



public void showDialog() {
        dialog = ProgressDialog.show(this, "", "");
    }

public void dismissDialog() {
    try {
        dialog.dismiss();
    } catch (Exception e) {
        Log.i(LOGTAG, e.getMessage()); //Crash application
    }

    }

尝试调试失败。Log.i(LOGTAG, e.getMessage());在dismissDialog() 中导致应用程序崩溃。

java.lang.RuntimeException:在 com.t.network.MainActivity$1@40519848 中接收广播 Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000000 (has extras) } 时出错

引起:java.lang.NullPointerException: println 需要一条消息

我如何使用进度/警报对话框来收听连接?

感谢

附言

Log.i(LOGTAG, "Network Type: " + mTypeName 
                    + ", subtype: " + mSubtypeName
                    + ", available: " + mAvailable + " isConnected: " + info.isConnected());

工作正常

PPS 我为我的英语道歉 :)

4

0 回答 0