广播接收器永远不会被呼叫

时间:2011-03-15 09:14:26

标签: android broadcastreceiver

我正在尝试学习广播接收器如何工作,但我没有成功,我的接收器从未被调用过。你们能指出我正确的方向吗?

以下是代码:

Main.java

public class Main extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent = new Intent(getApplicationContext(), OutgoingReceiver.class);
    intent.setAction("com.javaGroup.broadcastReceiver.views.TEST");
    sendBroadcast(intent);

  }
}

OutgoingReceiver.java

public class OutgoingReceiver extends BroadcastReceiver {

  public static final String CUSTOM_INTENT = "com.javaGroup.broadcastReceiver.views.TEST";

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("HIT OUTGOING-----------------------------------","");
    Intent i = new Intent();
    i.setAction(CUSTOM_INTENT);
    context.sendBroadcast(i);
  }
}

IncomingReceiver.java

public class IncomingReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(OutgoingReceiver.CUSTOM_INTENT)) {
      Log.d("GOT THE INTENT-------------------------------","");
    }
  }
}

的Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.javaGroup.broadcastReceiver.views" android:versionCode="1"
    android:versionName="1.0">
   <uses-sdk android:minSdkVersion="8" />

   <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

   <application android:icon="@drawable/icon" android:label="@string/app_name">
      <activity android:name="com.javaGroup.broadcastReceiver.views.Main" 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=".OutgoingReceiver" android:enabled="true">
         <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE"></action>
         </intent-filter>
      </receiver>

      <receiver android:name=".IncomingReceiver" android:enabled="true">
         <intent-filter>
            <action android:name="com.javaGroup.broadcastReceiver.views.TEST"></action>
         </intent-filter>
      </receiver>

    </application>
</manifest>

我哪里错了?

2 个答案:

答案 0 :(得分:0)

您需要在Manifest中为接收者添加正确的权限。见list of permissions

答案 1 :(得分:0)

当然你不会得到它,你的BCR(即OutgoingReceiver)没有注册听你的活动(主要)的Intent(com.javaGroup.broadcastReceiver.views.TEST)正在广播。

注意

您应该在代码中写下更多注释,以便您了解自己在做什么。就目前而言,我只能猜测。您应该了解活动生命周期以及您尝试执行的操作的完整行为。通过查看您的代码,这并不完全清楚。