尝试使用文本到语音时大声说出文本消息时出现NullPointerException

时间:2015-01-15 17:07:52

标签: java android nullpointerexception sms text-to-speech

我试图在发送文字到语音时收到Exception,并在到达时说短信,并且它给了我一个NullPointerException,我似乎可以理解是它想要我做什么或错误到底在哪里。什么可能是我的问题?

错误记录

java.lang.RuntimeException: Unable to start receiver com.fegeley.handsfreetexting.TTS: java.lang.NullPointerException
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2677)
        at android.app.ActivityThread.access$1800(ActivityThread.java:170)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5635)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.fegeley.handsfreetexting.TTS.speakText(TTS.java:52)
        at com.fegeley.handsfreetexting.TTS.onReceive(TTS.java:74)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2669)
        at android.app.ActivityThread.access$1800(ActivityThread.java:170)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5635)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
        at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

package com.fegeley.handsfreetexting;

import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Locale;


public class MainActivity extends ActionBarActivity {

TTS tts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tts = new TTS();
    tts.giveContext(this);
}

@Override
public void onPause(){
    tts.onPause();
    super.onPause();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

TTS.java

package com.fegeley.handsfreetexting;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;

import java.util.HashMap;
import java.util.Locale;

/**
 * Created by Kayne on 1/14/2015.
 */
public class TTS extends BroadcastReceiver {

private static Context context;
TextToSpeech tts;

public TTS(){
}

public static void giveContext(Context con){
    context = con;
}

protected void onCreate(Bundle savedInstanceState){
    tts = new TextToSpeech(context,
            new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    if(status != TextToSpeech.ERROR){
                        tts.setLanguage(Locale.US);
                    }
                }
            });
}

public void onPause(){
    if(tts !=null){
        tts.stop();
        tts.shutdown();
    }
}

public void speakText(String toSpeak){
    HashMap<String, String> hash = new HashMap<String,String>();
    hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
            String.valueOf(AudioManager.STREAM_NOTIFICATION));
    tts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, hash);
}

@Override
public void onReceive(Context context, Intent intent) {
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    //if (bundle != null)
    //{
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        //}
        //---display the new SMS message---
        speakText(str);
    }
}
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fegeley.handsfreetexting" >

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="com.fegeley.handsfreetexting.TTS">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>
</application>

<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

</manifest>

3 个答案:

答案 0 :(得分:1)

第52行的“tts”对象为NULL。

您似乎是在BroadcastReceiver的“onCreate()”中初始化它。

protected void onCreate(Bundle savedInstanceState){
    tts = new TextToSpeech(context,
            new TextToSpeech.OnInitListener()

请注意,BroadcastReceiver类没有任何onCreate()活动样式的回调方法。

我猜你假设系统会调用BroadcastReceiver类的onCreate()。对于BroadcastReceiver来说,情况并非如此。

您可以在onReceive()中初始化“tts”对象,如下所示:

public void onReceive(Context context1, Intent intent) {
    //---get the SMS message passed in---

    tts = new TextToSpeech(context,
            new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    if(status != TextToSpeech.ERROR){
                        tts.setLanguage(Locale.US);
                    }
                }
            });

此外,更改 MainActivity.java

中的以下行

删除:tts.giveContext(this);添加:TTS.giveContext(getApplicationContext());

此更改是为了防止 ReceiverCallNotAllowedException

答案 1 :(得分:1)

您无法在广播接收器中实例化TextToSpeech对象。你的代码

speakText(str);
onReceive末尾的

在文本到语音呼叫onInit之前被调用,因此您说话失败并未绑定到TTS引擎。
当SMS到达时,系统会实例化清单中定义的TTS对象。它与您在MainActivity中实例化的tts无关 您的应用程序打开时没有得到NPE,因为static类中的context TTS声明并且您在MainActivity中实例化了一个对象,因此context不为空,因此您在ttsonCreate中声明为 AADTechnical 建议的onReceive对象不为空。
当您的应用程序关闭时,tts中声明的MainActivity对象将被销毁,因此任何context对象中的TTS成员都会在没有一个调用giveContext的情况下启动。系统在实例化giveContext对象时不会调用TTS,因此context为空,并且类中的tts对象实例化为空并且得到NPE 1}}。

您需要做的是创建一个service类,其中实例化TTS对象并在onReceive

中启动您的服务
public class SMSService extends Service
{
    // instantiate a TTS object in this class
}

public class TTS extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // get your SMS message
        // and then start the SMSService passing the message in the intent bundle
    }

}

答案 2 :(得分:0)

我不知道库但是堆栈跟踪告诉第52行TTS.java中发生了NullPointerException:

str += "SMS from " + msgs[i].getOriginatingAddress();

这意味着msgs [i]为空虽然在此之前分配了一行:

msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

因此createFromPdu返回null。 由于createFromPdu似乎是一个框架方法,因此很可能从bundle中检索到的pdus [i]为null。 请确保您已经写过&#34; pdus&#34;在阅读之前进入捆绑。

的问候, 最大