Android的语音识别服务空指针异常

Android的语音识别服务空指针异常

本文介绍了Android的语音识别服务空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Android的语音服务认可下这里的例子:

Android语音识别连续服务

和下面是我的code:

 公共类MainActivity延伸活动{    私人诠释mBindFlag;
    信使mServiceMessenger;
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        上下文activityContext = getApplicationContext();
        意向书的服务=新意图(activityContext,VoiceCommandService.class);
        activityContext.startService(服务);
        mBindFlag = Build.VERSION.SDK_INT< Build.VERSION_ codeS.ICE_CREAM_SANDWICH? 0:Context.BIND_ABOVE_CLIENT;
    }    私人最终ServiceConnection mServiceConnection =新ServiceConnection()
    {
        @覆盖
        公共无效onServiceConnected(组件名名称,服务的IBinder)
        {
            //如果(调试){Log.d(TAGonServiceConnected);} // $ NON-NLS-1 $            mServiceMessenger =新使者(服务);
            消息味精=新的Message();
            msg.what = VoiceCommandService.MSG_RECOGNIZER_START_LISTENING;
            VoiceCommandService voiceCommandService =新VoiceCommandService();
            尝试
            {
                voiceCommandService.mServerMessenger.send(MSG);
            }
            赶上(RemoteException的E)
            {
                e.printStackTrace();
            }
        }        @覆盖
        公共无效onServiceDisconnected(组件名名)
        {
           //如果(调试){Log.d(TAGonServiceDisconnected);} // $ NON-NLS-1 $
            mServiceMessenger = NULL;
        }    };
    @覆盖
    保护无效调用onStart()
    {
        super.onStart();        bindService(新意图(这一点,VoiceCommandService.class),mServiceConnection,mBindFlag);
    }    公共类VoiceCommandService延伸服务
    {
    保护AudioManager mAudioManager;
    保护SpeechRecognizer mSpeechRecognizer;
    保护意图mSpeechRecognizerIntent;
    保护最终信使mServerMessenger =新信使(新IncomingHandler(本));    保护布尔mIsListening;
    保护挥发性布尔mIsCountDownOn;    静态最终诠释MSG_RECOGNIZER_START_LISTENING = 1;
    静态最终诠释MSG_RECOGNIZER_CANCEL = 2;
    @覆盖
    公共无效的onCreate()
    {
        super.onCreate();
        mAudioManager =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(本);
        mSpeechRecognizer.setRecognitionListener(新SpeechRecognitionListener());
        mSpeechRecognizerIntent =新意图(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                         RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                         this.getPackageName());
    }    保护类IncomingHandler扩展了Handler
    {
        私人的WeakReference< VoiceCommandService> mtarget;        IncomingHandler(VoiceCommandService目标)
        {
            mtarget =新的WeakReference< VoiceCommandService>(目标);
        }
        @覆盖
        公共无效的handleMessage(消息MSG)
        {
            最终VoiceCommandService目标= mtarget.get();            开关(msg.what)
            {
                案例MSG_RECOGNIZER_START_LISTENING:                    如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.JELLY_BEAN)
                    {
                        //关闭蜂鸣声
                        target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM,FALSE);
                    }
                     如果(!target.mIsListening)
                     {
                         target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
                         target.mIsListening = TRUE;
                        //Log.d(TAG,消息开始听); // $ NON-NLS-1 $
                     }
                     打破;                 案例MSG_RECOGNIZER_CANCEL:
                      target.mSpeechRecognizer.cancel();
                      target.mIsListening = FALSE;
                      //Log.d(TAG,消息取消识别); // $ NON-NLS-1 $
                      打破;
             }
       }
    }    //倒计时定时器果冻豆解决
    保护CountDownTimer mNoSpeechCountDown =新CountDownTimer(5000,5000)
    {        @覆盖
        公共无效onTick(长millisUntilFinished)
        {
            // TODO自动生成方法存根        }        @覆盖
        公共无效onFinish()
        {
            mIsCountDownOn = FALSE;
            消息消息= Message.obtain(NULL,MSG_RECOGNIZER_CANCEL);
            尝试
            {
                mServerMessenger.send(消息);
                消息= Message.obtain(NULL,MSG_RECOGNIZER_START_LISTENING);
                mServerMessenger.send(消息);
            }
            赶上(RemoteException的E)
            {            }
        }
    };    @覆盖
    公共无效的onDestroy()
    {
        super.onDestroy();        如果(mIsCountDownOn)
        {
            mNoSpeechCountDown.cancel();
        }
        如果(mSpeechRecognizer!= NULL)
        {
            mSpeechRecognizer.destroy();
        }
    }    保护类SpeechRecognitionListener实现RecognitionListener
    {        私有静态最后弦乐TAG =SpeechRecognitionListener;        @覆盖
        公共无效onBeginningOfSpeech()
        {
            //语音输入将被处理,所以没有必要为向下计数了
            如果(mIsCountDownOn)
            {
                mIsCountDownOn = FALSE;
                mNoSpeechCountDown.cancel();
            }
            //Log.d(TAGonBeginingOfSpeech); // $ NON-NLS-1 $
        }        @覆盖
        公共无效onBufferReceived(字节[]缓冲区)
        {        }        @覆盖
        公共无效onEndOfSpeech()
        {
            //Log.d(TAGonEndOfSpeech); // $ NON-NLS-1 $
         }        @覆盖
        公共无效onerror的(INT错误)
        {
            如果(mIsCountDownOn)
            {
                mIsCountDownOn = FALSE;
                mNoSpeechCountDown.cancel();
            }
             mIsListening = FALSE;
             消息消息= Message.obtain(NULL,MSG_RECOGNIZER_START_LISTENING);
             尝试
             {
                    mServerMessenger.send(消息);
             }
             赶上(RemoteException的E)
             {             }
            //Log.d(TAG,错误=+误差); // $ NON-NLS-1 $
        }        @覆盖
        公共无效的onEvent(INT EVENTTYPE,捆绑PARAMS)
        {        }        @覆盖
        公共无效onPartialResults(捆绑partialResults)
        {        }        @覆盖
        公共无效onReadyForSpeech(捆绑PARAMS)
        {
            如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.JELLY_BEAN)
            {
                mIsCountDownOn =真;
                mNoSpeechCountDown.start();
                mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM,FALSE);
            }
            //Log.d(TAGonReadyForSpeech); // $ NON-NLS-1 $
        }        @覆盖
        公共无效onResults(捆绑结果)
        {
            //Log.d(TAGonResults); // $ NON-NLS-1 $
            Toast.makeText(getApplicationContext(),这是我的吐司消息!=),
                       Toast.LENGTH_LONG).show();
        }        @覆盖
        公共无效onRmsChanged(浮动rmsdB)
        {        }    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        // TODO自动生成方法存根
        返回mServerMessenger.getBinder();
    }
    }
}

有人可以帮我找出为什么我遇到了空指针异常与 mTarget.AudioManager mTarget.SpeechRecognitionIntent ?我也看到我的服务onCreate方法是不是击中。能否请你告诉我正确的方法呢?

更新 - 在尝试调用服务的BindService方法,但没有被调用我的服务onCreate方法。可否请您指出我是什么不见了?


解决方案

  VoiceCommandService voiceCommandService =新VoiceCommandService()

不要实例化服务新 - 生命周期的方法,如的onCreate()不会被调用。

使用的意图

i am trying to create an android speech recognitions service following the example here:

Android Speech Recognition Continuous Service

and below is my code:

public class MainActivity extends Activity {

    private int mBindFlag;
    Messenger mServiceMessenger;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context activityContext = getApplicationContext();
        Intent service = new Intent(activityContext, VoiceCommandService.class);
        activityContext.startService(service);
        mBindFlag = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH ? 0 : Context.BIND_ABOVE_CLIENT;
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            //if (DEBUG) {Log.d(TAG, "onServiceConnected");} //$NON-NLS-1$

            mServiceMessenger = new Messenger(service);
            Message msg = new Message();
            msg.what = VoiceCommandService.MSG_RECOGNIZER_START_LISTENING;
            VoiceCommandService voiceCommandService = new VoiceCommandService();
            try
            {
                voiceCommandService.mServerMessenger.send(msg);
            }
            catch (RemoteException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
           //if (DEBUG) {Log.d(TAG, "onServiceDisconnected");} //$NON-NLS-1$
            mServiceMessenger = null;
        }

    };
    @Override
    protected void onStart()
    {
        super.onStart();

        bindService(new Intent(this, VoiceCommandService.class), mServiceConnection, mBindFlag);
    }

    public class VoiceCommandService extends Service
    {
    protected AudioManager mAudioManager;
    protected SpeechRecognizer mSpeechRecognizer;
    protected Intent mSpeechRecognizerIntent;
    protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));

    protected boolean mIsListening;
    protected volatile boolean mIsCountDownOn;

    static final int MSG_RECOGNIZER_START_LISTENING = 1;
    static final int MSG_RECOGNIZER_CANCEL = 2;


    @Override
    public void onCreate()
    {
        super.onCreate();
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
        mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                         RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                         this.getPackageName());
    }

    protected class IncomingHandler extends Handler
    {
        private WeakReference<VoiceCommandService> mtarget;

        IncomingHandler(VoiceCommandService target)
        {
            mtarget = new WeakReference<VoiceCommandService>(target);
        }


        @Override
        public void handleMessage(Message msg)
        {
            final VoiceCommandService target = mtarget.get();

            switch (msg.what)
            {
                case MSG_RECOGNIZER_START_LISTENING:

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
                    {
                        // turn off beep sound
                        target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
                    }
                     if (!target.mIsListening)
                     {
                         target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
                         target.mIsListening = true;
                        //Log.d(TAG, "message start listening"); //$NON-NLS-1$
                     }
                     break;

                 case MSG_RECOGNIZER_CANCEL:
                      target.mSpeechRecognizer.cancel();
                      target.mIsListening = false;
                      //Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
                      break;
             }
       }
    }

    // Count down timer for Jelly Bean work around
    protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
    {

        @Override
        public void onTick(long millisUntilFinished)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish()
        {
            mIsCountDownOn = false;
            Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
            try
            {
                mServerMessenger.send(message);
                message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
                mServerMessenger.send(message);
            }
            catch (RemoteException e)
            {

            }
        }
    };

    @Override
    public void onDestroy()
    {
        super.onDestroy();

        if (mIsCountDownOn)
        {
            mNoSpeechCountDown.cancel();
        }
        if (mSpeechRecognizer != null)
        {
            mSpeechRecognizer.destroy();
        }
    }

    protected class SpeechRecognitionListener implements RecognitionListener
    {

        private static final String TAG = "SpeechRecognitionListener";

        @Override
        public void onBeginningOfSpeech()
        {
            // speech input will be processed, so there is no need for count down anymore
            if (mIsCountDownOn)
            {
                mIsCountDownOn = false;
                mNoSpeechCountDown.cancel();
            }
            //Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
        }

        @Override
        public void onBufferReceived(byte[] buffer)
        {

        }

        @Override
        public void onEndOfSpeech()
        {
            //Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
         }

        @Override
        public void onError(int error)
        {
            if (mIsCountDownOn)
            {
                mIsCountDownOn = false;
                mNoSpeechCountDown.cancel();
            }
             mIsListening = false;
             Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
             try
             {
                    mServerMessenger.send(message);
             }
             catch (RemoteException e)
             {

             }
            //Log.d(TAG, "error = " + error); //$NON-NLS-1$
        }

        @Override
        public void onEvent(int eventType, Bundle params)
        {

        }

        @Override
        public void onPartialResults(Bundle partialResults)
        {

        }

        @Override
        public void onReadyForSpeech(Bundle params)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            {
                mIsCountDownOn = true;
                mNoSpeechCountDown.start();
                mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
            }
            //Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
        }

        @Override
        public void onResults(Bundle results)
        {
            //Log.d(TAG, "onResults"); //$NON-NLS-1$
            Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
                       Toast.LENGTH_LONG).show();
        }

        @Override
        public void onRmsChanged(float rmsdB)
        {

        }

    }



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return mServerMessenger.getBinder();
    }
    }


}

Can someone please help me find out why am running into nullpointer exception with mTarget.AudioManager and mTarget.SpeechRecognitionIntent? i also see that my service OnCreate method is not getting hit. Can please tell me the right approach?

update - am trying to invoke the service in the BindService method, yet my Oncreate method in the service is not being invoked. Can please point out what am missing?

解决方案
VoiceCommandService voiceCommandService = new VoiceCommandService()

Don't instantiate services with new - lifecycle methods such as onCreate() won't get invoked.

Use an Intent.

这篇关于Android的语音识别服务空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 16:37