Android的 - 在广播意图自定义操作(Android - Custom action in B

2019-10-22 06:24发布

我想允许用户发布评论时,他是离线这样,每当无线/互联网正在开启他的评论将我使用BroadCastReceiver.But我有问题要posted.Fot的是,它是永远不会里面if (intent.getAction().equals("commentpost"))如果我尝试点击postcomment.However它不进去后在WiFi开关if (wifi.isAvailable() || mobile.isAvailable())每当我在wifi开关。我不明白我要去的地方wrong.My日志显示“网络可用”,但从来没有显示“发布评论”。

    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>

Answer 1:

您需要将您的自定义操作添加到intent-filter你的BroadcastReceiver 。 只有这样,该Intent触发BroadcastReceiver

<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"/>
    <action android:name="commentpost"/>
</intent-filter>


文章来源: Android - Custom action in Broadcast Intent