0

我对以下用于获取媒体按钮操作的代码有疑问。

类 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)
4

1 回答 1

1

您需要检查 MediaButtonIntentReceiver 源中的确切第 26 行。我只能间接得出结论,您需要为事件检查 null,因为它可以为 null。

于 2013-07-16T01:44:24.027 回答