当用户按下音量调高按钮时,我需要启动通知,我无法直接在 sherlockfragment 上获得 keydown,所以我创建了一个从 sherlockfragmentactivity 调用的方法,但是我在 intent.putExtras 上得到一个空指针异常(捆)
这是我的 SherlockFragmentActivity 的代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
((MyFragment) mTabsAdapter.getItem(0)).myOnKeyDown(keyCode);
return super.onKeyDown(keyCode, event);
}
SherlockFragment 中的代码:
@Override
public void onActivityCreated (Bundle savedInstanceState)
{
intent = new Intent(getActivity(), NotifyService.class);
}
public void myOnKeyDown(int key_code){
if(key_code == KeyEvent.KEYCODE_VOLUME_UP){
notifyBar();
}
}
服务意图方法:
public void notifyBar(){
Bundle bundle = new Bundle();
bundle.putLong("data1", d1);
bundle.putLong("data2", d2);
intent.putExtras(bundle); // NPE HERE
getActivity().startService(intent);
}
日志猫:
07-28 00:04:28.587: E/AndroidRuntime(1737): FATAL EXCEPTION: main
07-28 00:04:28.587: E/AndroidRuntime(1737): java.lang.NullPointerException
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.my.app.MyFragment.notifyBar(MyFragment.java:692)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.my.app.MyFragment.myOnKeyDown(MyFragment.java:393)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.my.app.MyFragmentActivity.onKeyDown(MyFragmentActivity.java:171)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.view.KeyEvent.dispatch(KeyEvent.java:1037)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.app.Activity.dispatchKeyEvent(Activity.java:2068)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.actionbarsherlock.app.SherlockFragmentActivity.dispatchKeyEvent(SherlockFragmentActivity.java:122)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.view.ViewRoot.handleMessage(ViewRoot.java:1735)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.os.Looper.loop(Looper.java:123)
07-28 00:04:28.587: E/AndroidRuntime(1737): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 00:04:28.587: E/AndroidRuntime(1737): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 00:04:28.587: E/AndroidRuntime(1737): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 00:04:28.587: E/AndroidRuntime(1737): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 00:04:28.587: E/AndroidRuntime(1737): at dalvik.system.NativeStart.main(Native Method)