广播接收器不能与<receiver ... =“”> </receiver>一起使用

时间:2011-10-30 18:23:06

标签: android broadcastreceiver

我正在尝试创建一个小项目:Activity有一个发送广播的Button。广播接收器在收到消息时显示Toast。但广播从未收到过。

发信人:

    public class Task2Activity extends Activity implements OnClickListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View myButton = findViewById(R.id.broadcast_button);
        myButton.setOnClickListener(this);
    }
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.broadcast_button:
        Intent active = new Intent("yury.ku.SIMPLE_BROADCAST");
        this.sendBroadcast(active);
        break;
        }
    }
}

接收器:

public class SimpleReceiver extends BroadcastReceiver {

    @Override
     public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Toast.makeText(context, "Broadcast received" , Toast.LENGTH_LONG).show();
        if (action.equals("yury.ku.SIMPLE_BROADCAST")) {
            Toast.makeText(context, "Broadcast received" , Toast.LENGTH_LONG).show();
        }
    }
}

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="yury.ku"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:enabled="true">
        <activity android:name=".Task2Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="yury.ku.SIMPLE_BROADCAST"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <reciever android:name=".SimpleReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="yury.ku.SIMPLE_BROADCAST"/>
            </intent-filter>
        </reciever>

    </application>
</manifest>

1 个答案:

答案 0 :(得分:2)

我认为这个问题的答案是“我在e之前,除了c之后”。 : - )

您的XML中拼错了receiver

<reciever android:name=".SimpleReciever" android:enabled="true" android:exported="true">
    <intent-filter>
        <action android:name="yury.ku.SIMPLE_BROADCAST"/>
    </intent-filter>
</reciever>

应该是:

<receiver ... >
</receiver>

http://developer.android.com/guide/topics/manifest/receiver-element.html