Android - Broadcast Intent中的自定义操作

时间:2015-03-12 13:27:06

标签: android android-intent broadcastreceiver intentfilter android-broadcast

我试图允许用户在离线时发表评论,这样每当打开wifi /互联网时,他的评论就会被发布。我说我正在使用BroadCastReceiver.But我遇到的问题是它永远不会去在if (intent.getAction().equals("commentpost"))内,如果我点击postcomment后尝试打开wifi。但是每当我打开wifi时它都会进入if (wifi.isAvailable() || mobile.isAvailable())。我无法理解我哪里出错。我的日志显示“网络可用”但从未显示“发表评论”。

    commentpost.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
  Intent intent = new Intent();
                intent.setAction("commentpost");
                mContext.sendBroadcast(intent);
}
}


public class NetworkChangeReceiver extends BroadcastReceiver {

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

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable())
        {
           Log.e("Network Available", "Flag No 1");
            if (intent.getAction().equals("commentpost")) {
                Log.e("posting comment", "Flag No 2");
          postComment();
            }
        }
    }
}

清单

<receiver android:name="xyz.NetworkChangeReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE"></action>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
            </intent-filter>
        </receiver>

1 个答案:

答案 0 :(得分:2)

您需要将自定义操作添加到intent-filter的{​​{1}}。只有这样,BroadcastReceiver才会触发您的Intent

BroadcastReceiver