2011-03-29 106 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>