如何使用BroadcastReceiver获取网络状态变化?

时间:2014-11-11 14:00:57

标签: android android-asynctask broadcastreceiver

当我从wi-fi更改为3g或反之时,我的AsyncTask将导致错误。因此,当发生这种情况时,我想跟踪此并重新启动加载进度(或停止并在可能的情况下继续执行asynctask)。我在google上查了一下,发现当发生这种情况时会调用BroadcastReceiver onReceive。现在的问题是,当发生这种情况时,我仍然没有得到确切的时刻。

的onCreate

    registerReceiver(mConnReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

AsyncTask错误点(在HttpClient行上调用):

@Override
protected String doInBackground(String... params)
{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(params[0]);
    try
    {
        if(!isCancelled())//I have set this after I found the error
        {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
        }
    }

广播接收者

private BroadcastReceiver mConnReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        NetworkInfo changes = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        Log.w("current", "" + changes);
        if(noConnectivity)
        {
            task.cancel(true);
            task2.cancel(true);
            task3.cancel(true);
        }
        Log.w("taskIsCanceled","" + task.isCancelled());

    }
};

所以我有两个问题跟踪错误事件并重新启动或停止并继续执行asynctaskes。我有3个asynctaskes轮流。

当我从3g切换到wi-fi时,noConnectivity boolean总是返回我有连接。当我从wi-fi转到3g时,它首先返回我不会,之后不久(我连接)。

1 个答案:

答案 0 :(得分:0)

您可以使用反射来监控移动数据更改。

public class NetworkStateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getExtras() != null){
            final ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean mobileDataEnabled = false;

            try{
                Class cmClass = Class.forName(mConnectivityManager.getClass().getName());
                Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
                method.setAccessible(true); // Make the method callable
                mobileDataEnabled = (Boolean)method.invoke(mConnectivityManager);
            } catch(Exception e){
                return;
            }
            Toast.makeText(BackroundService.this, "Data state changed", Toast.LENGTH_LONG).show();
                    }
    }

}