如何从Broadcast Receiver调用TextToSpeech

时间:2013-03-19 10:54:16

标签: android broadcastreceiver text-to-speech android-broadcast

我的应用程序我正在呼叫广播接收器以读取传入的文本消息并大声说出来。我的广播接收器被正确调用,它正确地读取文本消息但是当涉及speak()方法时,它只是崩溃。这是我的代码:

这是BroadcastReceiver:

public class DrivingModeSpeaker extends BroadcastReceiver  {

            @Override
    public void onReceive(Context context, Intent intent) 
    {
        // TODO Auto-generated method stub
        int n;
        Bundle bundle=intent.getExtras();
        Object messages[]=(Object[])bundle.get("pdus");
        SmsMessage smsMessage[]=new SmsMessage[messages.length];
        for(n=0;n<messages.length;n++)
        {
            smsMessage[n]=SmsMessage.createFromPdu((byte[])messages[n]);

        }
        //show first message
        String sms1=smsMessage[0].getMessageBody();
        String from=smsMessage[0].getOriginatingAddress();
        Toast toast=Toast.makeText(context,"In DrivingModeSpeaker BR",1);
        toast.show();
        DrivingMode.speakSMS(sms1);

    }


}

这是包含speak()方法的DrivingMode.java:

public class DrivingMode extends Activity {
    private static TextToSpeech myTts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.message_m);
        myTts = new TextToSpeech(this,ttsInitListener);


    }

private TextToSpeech.OnInitListener ttsInitListener=new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int version) {
            // myTts.speak(""+o, 0 ,null);

        }
    };
    public static void speakSMS(String sms)
    {
        myTts.speak(sms,0,null);

    }


}

我在一个单独的项目中尝试过这个代码,它可以工作。但在我的主要项目中,它没有 - 可能是因为两个广播接收器发生冲突或其他什么?我不知道,我是Android的新手,请帮忙!

1 个答案:

答案 0 :(得分:3)

目前,您正尝试通过创建Activity的实例来调用Activity方法,如果Activity未运行,则通过NullPointerException创建。所以不要调用Activity的方法从BroadcastReceiver启动Activity并使用Intent.putExtra发送短信数据:

例如:

public void onReceive(Context context, Intent intent) 
    {
       // Your code here....
        Toast toast=Toast.makeText(context,"In DrivingModeSpeaker BR",1);
        toast.show();
        // start Activity here
        Intent intent  = new Intent(context,
                    DrivingMode.class);
            intent.putExtra("sms", sms);  //<<< put sms text
            context.startActivity(intent);   

    }

并在DrivingMode onCreate方法中获取短信数据并调用speakSMS方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.message_m);
        Bundle extras = getIntent().getExtras();
        myTts = new TextToSpeech(this,ttsInitListener);
        DrivingMode.speakSMS(extras.getString("sms"));

    }

还可以使用TextToSpeech.setOnUtteranceCompletedListener在Speak结尾处完成活动