Android:广播演示不起作用

时间:2012-04-08 03:57:48

标签: android android-intent android-emulator

我是Android的新手,我正在尝试广播演示,我尽力阅读文档,但它无法正常工作。请看一下我的代码:

BroadcastDemoActivity.java

package com.broadcastdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class BroadcastDemoActivity extends Activity {
    /** Called when the activity is first created. */
    public static final String PUBLIC_HOLIDAYS = "com.paad.action.PUBLIC_HOLIDAYS";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent = new Intent(PUBLIC_HOLIDAYS);
        intent.putExtra("Holiday", "8th April is a holiday");
        sendBroadcast(getIntent());
    }
}

Receive.java

package com.broadcastdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class Receive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String message = intent.getStringExtra("Holiday");
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

    }

}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.broadcastdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".BroadcastDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".Receive">
            <intent-filter>               
                <action android:name="com.paad.action.PUBLIC_HOLIDAYS"/>
            </intent-filter>            
        </receiver>
    </application>
</manifest>

我知道我错过了一些我不知道的事情,请帮忙。

1 个答案:

答案 0 :(得分:0)

我相信你的问题在于对sendBroadcast的调用。

    Intent intent = new Intent(PUBLIC_HOLIDAYS);
    intent.putExtra("Holiday", "8th April is a holiday");
    sendBroadcast(getIntent());

您没有发送构建的意图,而是发送从getIntent()返回的意图,这将是活动开始的意图。

应该是

    Intent intent = new Intent(PUBLIC_HOLIDAYS);
    intent.putExtra("Holiday", "8th April is a holiday");
    sendBroadcast(intent);