0

我有一个广播来检查网络,当网络改变状态时,我用 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();
    }
}

在我的Activity中,当我因为各种原因需要第一次调用sendBroadcast,但是Android crash :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");
    }
}

问题是什么 ?

先感谢您

4

1 回答 1

0

https://stackoverflow.com/a/17906435/2201919来自 @JoxTraex

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

请以不同的方式解决您的问题。

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

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

于 2014-01-03T16:14:35.393 回答