Android - Custom action in Broadcast Intent

此生再无相见时 提交于 2020-01-16 06:07:34

问题


I am trying to allow user to post comment when he is offline such that whenever wifi/internet is turned on his comment will be posted.Fot that I am using BroadCastReceiver.But the issue i am having is that it is never going inside if (intent.getAction().equals("commentpost")) if i try switching on wifi after clicking on postcomment.However it does go inside if (wifi.isAvailable() || mobile.isAvailable()) whenever i switch on wifi.I failed to understand where i am going wrong.My log shows "Network Available" but never shows "posting comment".

    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();
            }
        }
    }
}

Manifest

<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:


You need to add your custom action to the intent-filter of your BroadcastReceiver. Only then will that Intent trigger your 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>


来源:https://stackoverflow.com/questions/29011089/android-custom-action-in-broadcast-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!