2011-10-30 58 views
1

我想創建一個小項目:活動有一個按鈕,發送廣播。廣播接收器收到消息時會顯示Toast。但廣播從未收到。BroadcastReceiver無法與<reciever ...></reciever>

發件人:

public class Task2Activity extends Activity implements OnClickListener { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     View myButton = findViewById(R.id.broadcast_button); 
     myButton.setOnClickListener(this); 
    } 
    public void onClick(View v) { 
     switch (v.getId()) { 
     case R.id.broadcast_button: 
     Intent active = new Intent("yury.ku.SIMPLE_BROADCAST"); 
     this.sendBroadcast(active); 
     break; 
     } 
    } 
} 

接收機:

public class SimpleReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     final String action = intent.getAction(); 
     Toast.makeText(context, "Broadcast received" , Toast.LENGTH_LONG).show(); 
     if (action.equals("yury.ku.SIMPLE_BROADCAST")) { 
      Toast.makeText(context, "Broadcast received" , Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

清單:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="yury.ku" 
     android:versionCode="1" 
     android:versionName="1.0"> 
    <uses-sdk android:minSdkVersion="13" /> 

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:enabled="true"> 
     <activity android:name=".Task2Activity" 
        android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <action android:name="yury.ku.SIMPLE_BROADCAST"/> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <reciever android:name=".SimpleReceiver" android:enabled="true" android:exported="true"> 
      <intent-filter> 
       <action android:name="yury.ku.SIMPLE_BROADCAST"/> 
      </intent-filter> 
     </reciever> 

    </application> 
</manifest> 
+0

不能在廣播接收器創建Toast通知。你必須從一項活動或服務中敬酒。爲了從廣播接收者處敬酒,你需要使用一個處理程序,但是我真的不知道如何實現它。 – Jakar

回答

2

我認爲這個問題的答案是 「我信之前,除C後」。 :-)

你已經在你的XML拼錯receiver

<reciever android:name=".SimpleReciever" android:enabled="true" android:exported="true"> 
    <intent-filter> 
     <action android:name="yury.ku.SIMPLE_BROADCAST"/> 
    </intent-filter> 
</reciever> 

它應該是:

<receiver ... > 
</receiver> 

http://developer.android.com/guide/topics/manifest/receiver-element.html

+0

愚蠢的錯誤。謝謝。 – user1020946

+0

如果它解決了你的問題,那麼請點擊勾號將此問題標記爲已解決 - 謝謝! –

+0

@DanJ An _efficient_ answer。 –

相關問題