活动未收到广播

时间:2014-11-25 10:23:01

标签: android

这是我发现here最相似的问题,但是我无法让它发挥作用,有人可以帮助我吗?

ConectivityChange.java

public static final String MSG_EVENT = "com.example.miguel.broadcast.EVENT";

// onCreate...
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(MSG_EVENT);
intent.putExtra("type", "connection");
intent.putExtra("connected", networkConn);
intent.putExtra("network", 1);
intent.putExtra("name", ssid);
context.sendBroadcast(intent);

MainActivity.java

public static final String MSG_EVENT = "com.example.miguel.broadcast.EVENT";

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "Message");
    }
}

MyBroadcastReceiver mReceiver = new MyBroadcastReceiver();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentFilter filter = new IntentFilter();
    filter.addAction(MSG_EVENT);
    registerReceiver(mReceiver, filter);
}

AndroidManifiest.java

<activity android:name=".MainActivity" android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="com.example.miguel.broadcast.EVENT" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

1 个答案:

答案 0 :(得分:0)

它以这种方式工作:

Intent intent = new Intent();
intent.setAction(MSG_EVENT);
intent.addCategory(Intent.CATEGORY_DEFAULT);