我遇到以下代码的问题,无法获取媒体按钮的操作。
Class MediaButtonIntentReceiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = (KeyEvent) intent
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
Log.i("ok", "media button pressed");
}
}
if (isOrderedBroadcast()) {
abortBroadcast();
}
}
}
在我的主要内容中我有这个:
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(mMediaButtonReceiver, mediaFilter);
这是我清单上的接收器
<receiver android:name="ch.bono88.Ederly.MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
所以当我尝试执行我的应用程序时,我得到了这个异常
java.lang.RuntimeException: Unable to start receiver ch.bono88.Ederly.MediaButtonIntentReceiver: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at ch.bono88.Ederly.MediaButtonIntentReceiver.onReceive(MediaButtonIntentReceiver.java:26)
答案 0 :(得分:1)
您需要检查MediaButtonIntentReceiver源中的确切第26行。我可以间接地断定你需要为事件检查null,因为它可以为null。