2011-03-29 92 views
9

我试图让广播接收器工作。应尽可能的简单,我有我的表现是这样的:Android广播接收器不工作

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.mytest.intentRec" android:versionCode="1" 
    android:versionName="1.0"> 
    <application android:icon="@drawable/icon" android:label="@string/app_name" 
     android:debuggable="true"> 
     <activity android:name=".mainAct" 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="com.mytest.intentRec.MyIntentRec" 
        android:enabled="true" > 
     </receiver> 
    </application> 
    <uses-sdk android:minSdkVersion="7" /> 
</manifest> 

正如你可以看到我有一个主要活动mainAct,这并不只是发送一旦开始广播:

public class mainAct extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     this.sendBroadcast(new Intent()); 
    } 
} 

和我有一个类MyIntentRec,这很简单,因为它可以:

public class MyIntentRec extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.v("IntentRec", "got it"); 
    } 
} 

我想到的是,当我开始我的应用程序,广播被发送和被拾起和日志条目是软件写ñ。我没有看到该日志条目,并且没有看到任何错误。我怀疑在清单中发送错误或发送广播。我只是在那里创建了一个空的意图,它是否需要某些特定的属性?

回答

7

setClass为你的意图,

EX:

public class mainAct extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Intent i=new Intent("any string"); 
     i.setClass(this, MyIntentRec.class); 
     this.sendBroadcast(i); 
    } 
} 

这就是它的意思是“没有任何过滤器意味着它只能由指定其确切的类名意向对象上调用“。

[老答案]
你应该注册您在清单中需要什么样的行动。
例如:

<receiver android:name="com.mytest.intentRec.MyIntentRec" android:enabled="true" > 
     <intent-filter> 
      <action android:name="your.intent" /> 
     </intent-filter> 
    </receiver> 

发送,

this.sendBroadcast(new Intent("your.intent")); 
+0

这工作得很好。但正如上面的评论中所发表的那样。我不需要一个意图过滤器。我会怎么做,而不意图过滤器? – AndyAndroid 2011-03-29 14:12:20

1

它不足以制造new Intent();。你必须用一些行动来指定它。此外,您必须在清单中指定此特定操作的意图过滤器。请阅读更多herehere

+0

根据http://developer.android.com/guide/topics/manifest/receiver-element.html我不需要有意图过滤器看到android:exported。 – AndyAndroid 2011-03-29 14:01:05

1

您没有在清单中为您的BroadcastReceiver定义任何意向过滤器。为自定义操作类型指定一个。您还必须在启动时在brodcast中的Intent中定义此自定义Action类型。

+0

请参阅上面有关意图过滤器的注释。 – AndyAndroid 2011-03-29 14:01:46

+0

如果你不想使用过滤器,那么你必须明确地解决您要发送您的意向书,在意向书的调性质的组件。你不要在你的代码中这样做。 – 2011-03-29 14:07:17

+0

也许我没有,因为我不知道该怎么......顺便说一句我仍然不知道... – AndyAndroid 2011-03-29 14:29:46

1

尝试指定什么样的行动接收机应在清单中赶。你可以这样做:

<receiver android:name="com.mytest.intentRec.MyIntentRec"> 
    <intent-filter> 
     <action android:name="android.intent.action.MEDIA_BUTTON" /> 
    </intent-filter> 
</receiver>