Android网络监听器

时间:2012-08-22 08:53:34

标签: android networking android-intent broadcastreceiver

请帮助解决问题。 任务:创建网络侦听器。当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
    }

    }

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

java.lang.RuntimeException:在com.t.network.MainActivity$1@40519848

中接收广播Intent {act = android.net.conn.CONNECTIVITY_CHANGE flg = 0x10000000(有额外内容)}时出错

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

如何使用Progress / Allert对话框监听连接?

感谢

P.S。

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

正常工作

P.P.S。我为我的英语道歉:)

0 个答案:

没有答案