问题
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