編輯:關於 Android 程式設計
用耳機聽音樂時,如果能直接按耳機上的線控切換上一首/下一首,體驗會好很多。本文記錄我怎麼把這個功能做出來。
動手之前要先釐清兩件事:(1)耳機按鍵事件怎麼攔截,短按與長按如何分辨;(2)上一首/下一首實際上該怎麼觸發。兩題解決之後,剩下的就是把它們串起來。
先確認按鍵事件有沒有往上拋到 framework 層。插上耳機、接上 log 工具,觀察印出來的訊息:
01-01 01:07:44.524: D/WindowManager(514): interceptKeyTi keyCode=85 down=false repeatCount=0 keyguardOn=false mHomePressed=false canceled=false 01-01 01:07:47.644: D/WindowManager(514): interceptKeyTi keyCode=86 down=true repeatCount=0 keyguardOn=false mHomePressed=false canceled=false
從 log 可以看出:長按耳機線控對應 keyCode=86,短按對應 keyCode=85。而 PhoneWindowManager.java 裡的 interceptKeyBeforeQueueing 就是按鍵事件進入系統的入口函式。
音樂播放其實跑在一個 Service 裡,也就是 Music 中的 MediaPlaybackService。看它的 onStartCommand 就會發現,播放行為是靠 Intent 帶回來的不同參數來決定的:暫停、播放、上一首、下一首等等。
關鍵在於耳機事件怎麼傳進音樂 App。Service 的父類是 ContextWrapper,不像 Activity 那樣實作了 Window.Callback 與 KeyEvent.Callback,因此根本收不到按鍵事件。
解法是 BroadcastReceiver:在音樂 App 裡宣告一個 Receiver,再由 PhoneWindowManager 把攔截到的事件用廣播丟過來。整體思路就是這樣,以下是幾個實作上容易踩到的細節。
因為監聽的是 App 外部的廣播,程式碼動態註冊並不可靠,必須寫在 AndroidManifest.xml 裡,而且 android:exported="true" 是必要的:
<receiver android:name="com.android.music.HEADSET_key_Receiver"
android:exported="true" >
<intent-filter>
</intent-filter>
</receiver>
Intent intent = new Intent();
intent.putExtra("music_change", music_change);
intent.setClassName("com.android.music", "com.android.music.HEADSET_key_Receiver");
intent.setAction("com.android.music.HEADSET_key_input");
這裡建議用 setClassName 明確指定目標元件,效率比只丟 action 好得多。
在 PhoneWindowManager 中攔截到的事件請取 down 的那一次,避免一次按鍵觸發兩回。
boolean isMusicActive() {
final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
if (am == null) {
Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
return false;
}
return am.isMusicActive();
}
另外也要確認目前沒有通話中(incall),否則會在來電或通話時誤觸播放:
ITelephony telephonyService = getTelephonyService();
if (telephonyService != null) {// 這裡檢測一下是否當前正在通常 incall
try {
if (!telephonyService.isIdle()) {
// Suppress PLAY/PAUSE toggle when phone is ringing or in-call
// to avoid music playback.
return;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException", ex);
}
}
private boolean isMusicServiceRunning(Context context) {
boolean isServiceRuning = false;
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
final int maxServciesNum = 100;
List<RunningServiceInfo> list = am.getRunningServices(maxServciesNum);
for (RunningServiceInfo info : list) {
if (MediaPlaybackService.class.getName().equals(info.service.getClassName())) {
isServiceRuning = true;
break;
}
}
return isServiceRuning;
}
Service 在跑不代表正在播放(可能處於暫停狀態),而是否真的在播放只有 MediaPlaybackService 自己知道。所以啟動時要帶一個識別用的 extra:
Intent i = new Intent(context, MediaPlaybackService.class); i.setAction(MediaPlaybackService.SERVICECMD); i.putExtra(MediaPlaybackService.CMDNAME, command); i.putExtra(MediaPlaybackService.DELTATIME, deltaTime); i.putExtra(HEADSET_key_input, "true"); context.startService(i);
其中 i.putExtra(HEADSET_key_input, "true") 就是用來標示這次由耳機按鍵觸發,因此在 MediaPlaybackService.onStartCommand 中要有對應的判斷:
// yuyongjun _start 2014-4-16 FeatureOption.BASICOM_HEADSET_KEY_CONTROL_MUSIC_CHANGE_SONG
String HEADSET_key_input = intent.getStringExtra(HEADSET_key_Receiver.HEADSET_key_input);
if(HEADSET_key_input != null && HEADSET_key_input.equals("true"))
{
if(false == mIsSupposedToBePlaying)
{
return START_STICKY;
}
MusicLogUtils.d("yuyongjun", "onStartCommand: HEADSET_key_input");
}// yuyongjun _end 2014-4-16
這裡的 mIsSupposedToBePlaying 判斷很重要:如果使用者其實處於暫停狀態,就直接返回、不做任何事,避免按一下耳機反而開始播放。
Eclipse 注釋模板的配置與使用(圖文詳解)
規範的代碼注釋能顯著提升可讀性與團隊協作效率。Eclipse 支持自定義注釋模板,讓新建文件、類和方法時自動生成標準注釋。以下介紹具體配置方法。 一、配置入口 在首選項中
Android 開發筆記:統計分析 SDK 集成指南
用戶畫像 對程序員來說,用戶畫像就是用戶的屬性和行為;通俗地說,用戶畫像包括了個人信息、興趣愛好、日常行為等有血有肉的客戶實體。用戶畫像是精準營銷的產物,企業透過收集用戶
自定義 AutoCompleteTextView 實現多字段模糊匹配
AutoCompleteTextView 很多人都用過,某些場景下直接用 Google 提供的 ArrayAdapter 就能滿足需求。但在實際開發中,我們往往得自己動手
Android 開源元件 MenuDrawer:打造側滑選單菜單
MenuDrawer 是一個與 SlidingMenu 概念相近的開源框架,常用來實作「側滑菜單」效果——以 menu 作為設定選單,contentView 作為詳細頁面