2012-07-25 32 views
0

我想檢測音頻耳機以播放音頻文件。但我需要檢測耳機是否已連接或不是每個標籤,如專輯,藝術家,播放列表等等。我正在創建單獨的asynctask來檢測每個選項卡中的設備。它的工作正常。但如果我給應用程序更多的壓力,比如快速切換標籤。我的應用程序的GUI我得到冷凍。我認爲它運行更多的線程或線程池被甩了。Android :: Background跨應用程序

所以我有一個其他的想法,只有一個後臺線程將運行檢查設備的連接和功能。我們需要將該狀態分享到應用程序中的任何地方。但我不知道如何實現它。

任何想法或示例代碼?

檢查this Post另外。

回答

0

爲了檢測耳機插頭容易的工作一樣USB檢測一個需要註冊與行動機器人接收器:NAME =「android.intent.action.ACTION_HEADSET_PLUG」 />和接收器會主動

公共類PhoneUsbReceiver延伸的BroadcastReceiver {

@Override 
public void onReceive(Context context, Intent intent) { 
    Bundle extras = intent.getExtras(); 

    if (intent.getAction().equalsIgnoreCase(
      "android.intent.action.UMS_CONNECTED")){ 
     Toast.makeText(context, "Usb-connected..", Toast.LENGTH_SHORT) 
       .show(); 
     Log.i("Arpit", "USB connected.."); 
    } 
    if (intent.getAction().equalsIgnoreCase(
      "android.intent.action.UMS_DISCONNECTED")) { 
     Toast.makeText(context, "USB dis-connected..", Toast.LENGTH_SHORT) 
       .show(); 
     Log.i("Arpit", "USB dis-connected.."); 
    } 

    if (intent.getAction().equalsIgnoreCase(
      "android.intent.action.ACTION_HEADSET_PLUG")) { 
     Toast.makeText(context, "HEADSET_PLUG-connected..", 
       Toast.LENGTH_SHORT).show(); 
     Log.i("Arpit", "HEADSET_PLUG-connected.."); 
    } 

    if (intent.getIntExtra("state", 0) == 0) { 
     Toast.makeText(context, "HEADSET_PLUG-connected..", 
       Toast.LENGTH_SHORT).show(); 
     Log.i("Arpit", "HEADSET_PLUG-connected.."); 
    } else if (intent.getIntExtra("state", 0) == 1) { 
     Toast.makeText(context, "HEADSET_PLUG-dis-connected..", 
       Toast.LENGTH_SHORT).show(); 
     Log.i("Arpit", "HEADSET_PLUG-dis-connected.."); 
    } 

} 

}

現在宣佈接收機在清單:

<receiver android:name=".PhoneUsbReceiver" > 

      <intent-filter > 
       <action android:name="android.intent.action.UMS_CONNECTED" /> 
       <action android:name="android.intent.action.UMS_DISCONNECTED" /> 

       <action android:name="android.intent.action.ACTION_HEADSET_PLUG" /> 
      </intent-filter> 

     </receiver> 
0

要在選項卡之間共享數據,您可以創建一個HeadphoneHelper類並在靜態字段中記錄當前狀態。

例如爲:

public class HeadphoneHelper { 
    private static Boolean connected; 

    public static Boolean isConnected() { 
     return connected; 
    } 

    public static Boolean setConnected(Boolean isNowConnected) { 
     connected = isNowConnected; 
    } 


} 

,然後用它在你的標籤:

Boolean headphoneConnected = HeadphoneHelper.isConnected();