1

我正在寫一個應用程序,它捕獲bt-headset中的媒體按鈕點擊。但是,由於我的接收器是在清單文件中陳述的,我突然無法再控制我的活動,而我真正想要做的是在某人按下耳機按鈕時按下活動上的軟件按鈕。從單獨的broadcastreceiver更新活動,如何?

我試過幾種解決方案,但沒有任何工作。這是我目前的狀態

package com.siriforreq.activities; 


import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
public class MediaButtonReceiver extends BroadcastReceiver{ 
    private boolean gotMessage = false; 

    public MediaButtonReceiver(){ 
     super(); 
    } 

    public boolean isMessage(){ 
     return this.gotMessage; 
    } 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     System.out.println("IN ON RECEIVE1"); 
     if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { 


       System.out.println("GOT MEDIA BUTTON"); 
       Intent startBroadcastIntent = new Intent(context, NetworkActivity.class); 
       startBroadcastIntent.setAction("com.siriforerq.activities.ACTION_LOL"); 
       startBroadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 
       System.out.println("...sending broadcast"); 
       context.sendBroadcast(startBroadcastIntent); 



     } 
    } 


    } 

在上面的接收器,我確實趕上媒體按鈕。但是我現在從哪裏去更新我的活動?我現在想要做的是發送另一個自定義廣播,並在該活動的另一個接收器中捕獲該廣播,但似乎不起作用。這裏是我的活動:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_network); 


    mMediaReceiverCompName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName()); 
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 

    IntentFilter btCommunicationFilter = new IntentFilter(); 
    btCommunicationFilter.setPriority(1000); 
    btCommunicationFilter.addAction("com.siriforerq.activities.ACTION_LOL"); 
    catchButtonEvent = new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      System.out.println("Got broadcast yes"); 
      //startTalkInteraction(); <- this is the method I want to call in the activity   
     }  
    }; 
    registerReceiver(catchButtonEvent, btCommunicationFilter); 

} 

public void onResume() { 
    super.onResume(); 

    mAudioManager.registerMediaButtonEventReceiver(mMediaReceiverCompName); 
    socketNetworkHelper = SocketNetworkHelper.getSocketNetworkHelper(ip, port); 
    setButtonStatus(true); 

} 

在上面匿名接收器,即正在從MediaButtonReceiver發送不會被調用,這裏是我的問題,現在的廣播。我應該以另一種方式思考,或者爲什麼我的onReceive不在匿名接收器類觸發器中?

+0

你有申報所需的權限? – tundundun 2013-03-26 10:46:38

+0

哪個權限...? – 2013-03-26 10:50:40

回答

4

從文檔中可以看出,您使用的構造函數爲Intent(class,context),它爲特定組件創建了一個Intent。相反,你應該建立你的Intent是這樣的:在AndroidManifest.xml

Intent startBroadcastIntent = new Intent(); 
startBroadcastIntent.setAction("com.siriforerq.activities.ACTION_LOL"); 
startBroadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 
+1

Omg之前我確實有過這樣的情況(但是我想我在那個時候還有其他問題,因爲它現在正在工作)。非常感謝你,一直在努力。將在幾分鐘內批准並註冊 – stevietheTV 2013-03-26 10:54:29

相關問題