Android中事件监听示例
监视来电状态
AudioFocus是Android2.2以后才有的功能,对于比2.2低得版本,用的是另一种方法,就是监听电话的状态。最起码在电话打进来是能够暂停音乐的播放。
实现这一功能的第一步是在AndroidManifest.xml中声明用于接收PHONE_STATE通知的receiver
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
第二步是定义一个对应的PhoneStateReceiver,代码如下
package LyricPlayer.xwg;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//if android.os.Build.VERSION.SDK_INT >= 8 we use audio focus.
if (android.os.Build.VERSION.SDK_INT < 8){
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm.getCallState() != TelephonyManager.CALL_STATE_IDLE){
context.startService(new Intent(MediaPlayerService.ACTION_PAUSE));
}
}
}
}
这就够了。
监视耳机插头拔出
如果在音乐播放过程中拔出耳机,音乐就会通过扬声器播放出来。为了避免这种尴尬局面,我们会监视耳机拔出状态,并在耳机拔出时暂停播放。
首先是在AndroidManifest.xml中声明用于接收AUDIO_BECOMING_NOISY通知的receiver
<receiver android:name=".MusicIntentReceiver">
<intent-filter>
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
</intent-filter>
</receiver>
然后就是定义用于处理通知的receiver,类名要和AndroidManifest.xml中声明的一样。
package LyricPlayer.xwg;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MusicIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
ctx.startService(new Intent(LyricPlayerService.ACTION_PAUSE));
}
}
}
MEDIA_BUTTON处理
在讨论处理方法之前,必须先明确:那些键属于MEDIA_BUTTON?根据我的试验,MEDIA_BUTTON好像就是线控上面的上个按钮。网上也有用同样的方法取得音量键动作的内容,但是我没有试出来。
继续我们的话题,为了检测MEDIA_BUTTON需要一些准备工作。
首先是在AndroidManifest.xml中声明用于接收MEDIA_BUTTON通知的receiver
<receiver android:name="MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
当然需要定义真正的receiver,名字要和AndroidManifest.xml中的一样。
package LyricPlayer.xwg;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
public class MediaButtonReceiver extends BroadcastReceiver {
private static final String TAG = new String("LyricVolumeKeyReceiver");
@Override
public void onReceive(Context context, Intent intent) {
//MusicPlaybackService service = (MusicPlaybackService)context;
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent key = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if(key.getAction() == KeyEvent.ACTION_DOWN){
Log.i(TAG, "OnReceive, getKeyCode = " + key.getKeyCode());
switch(key.getKeyCode()){
case KeyEvent.KEYCODE_HEADSETHOOK :
context.startService(new Intent(MediaPlayerService.ACTION_PLAY_PAUSE));
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
context.startService(new Intent(MediaPlayerService.ACTION_PREVIOUS));
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
context.startService(new Intent(MediaPlayerService.ACTION_NEXT));
break;
}
}
}
}
}
比较特别的是中间的键的键值不是KEYCODE_PLAY_PAUSE而是KEYCODE_HEADSETHOOK。想想也是,接电话也用这个键。
准备工作的最后一步就是要把通过MediaButtonReceiver来接受MEDIA_BUTTON这件事报告给AudioMenager,由于这也是Android2.2及以后版本才有的功能,也需要做版本判断。
if (android.os.Build.VERSION.SDK_INT >= 8){
mReceiverName = new ComponentName(getPackageName(),MediaButtonReceiver.class.getName());
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.registerMediaButtonEventReceiver(mReceiverName);
}
当然在结束的时候我们也会保持取消登录的良好习惯。
if(mAudioManager != null && mReceiverName != null){
mAudioManager.unregisterMediaButtonEventReceiver(mReceiverName);
}
Notification表示
Notification表示首先取得NotificationManager
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
在需要表示的时候调用showNotification()方法。和showNotification()方法有关的代码:
public interface NotificationProvider{
public Notification createNotification(Context context);
}
NotificationProvider mNotificationProvider = null;
public void setNotificationProvider(NotificationProvider provider){
mNotificationProvider = provider;
}
/** * Show a notification while this service is running. */
private void showNotification() {
if(mNotificationProvider != null){
// Send the notification.
mNotificationManager.notify(NOTIFICATION, mNotificationProvider.createNotification(this));
}
}
已经用了N次的办法了。不用再解释了吧。当然,看看实现侧的做法还有必要的。
mProxy.setNotificationProvider(new MediaPlayerService.NotificationProvider(){
@Override
public Notification createNotification(Context context) {
Notification notification = new Notification(R.drawable.button_blue_play, mProxy.getTitle(), System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, LyricMain.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(context, getText(R.string.media_player_label), mProxy.getTitle(), contentIntent);
return notification;
}
});