ANDROID - 当我调用sendBroadcast来检查网络时崩溃

时间:2013-02-21 15:32:52

标签: android crash broadcastreceiver android-broadcast

我有一个广播来检查网络,当网络改变状态时,我通过onNetworkActivated()或onNetworkInactivated()通知我的活动:

public class NetworkBroadcastReceiver extends BroadcastReceiver
{
    private OnNetworkListener currentActivity = null;

    public NetworkBroadcastReceiver(FragmentActivity activity)
    {
        try
        {
            currentActivity = (OnNetworkListener) activity;
        }
        catch (ClassCastException e)
        {
            throw new ClassCastException(activity.toString() + " doit implémenter OnNetworkListener");
        }
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        ConnectivityManager connectivity = (ConnectivityManager)  
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivity == null)
        {
            currentActivity.onNetworkInactivated();
            return;
        }
        else 
        {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.getState() == NetworkInfo.State.CONNECTED)
            {
                 currentActivity.onNetworkActivated();
                 return;
            }
        }
        currentActivity.onNetworkInactivated();
    }

    public interface OnNetworkListener
    {
        public void onNetworkActivated();
        public void onNetworkInactivated();
    }
}

在我的活动中,当我第一次需要通过各种原因调用sendBroadcast,但Android崩溃:s

public class Earthquake extends FragmentActivity implements OnNetworkListener
{
    private FragmentManager fragmentManager;
    private NetworkBroadcastReceiver networkbroadcastreceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        fragmentManager = getSupportFragmentManager();
        networkbroadcastreceiver = new NetworkBroadcastReceiver(Earthquake.this);
        this.registerReceiver(networkbroadcastreceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        this.sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onDestroy()
    {
        this.unregisterReceiver(networkbroadcastreceiver);
        super.onDestroy();
    }

    public void onNetworkActivated()
    {
        Log.e("onNetworkActivated", "onNetworkActivated");
    }

    public void onNetworkInactivated()
    {
        Log.e("onNetworkInactivated", "onNetworkInactivated");
    }
}

有什么问题?

提前谢谢

1 个答案:

答案 0 :(得分:0)

https://stackoverflow.com/a/17906435/2201919 通过@ JoxTraex

您不得发送此广播。如果应用程序可以发送此广播,则可能会导致设备出现问题。这是受保护的系统广播。

请以不同的方式处理您的问题。

参考:http://developer.android.com/reference/android/net/ConnectivityManager.html

请注意,只有少数几种方法可以使用该操作。这意味着您无法发送此广播。