0

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

接收.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();

    }

}

清单.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>

我知道我遗漏了一些我不知道的东西,请帮忙。

4

1 回答 1

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);
于 2012-04-08T04:08:22.593 回答