简体   繁体   English

如何从其他活动或服务调用一个活动的 function?

[英]How to call function of one Activity from other Activity or service?

I need to call some functions from one activity.我需要从一项活动中调用一些功能。 But when I do that, it gives null pointer... error.但是当我这样做时,它会给出 null 指针...错误。 I am using this as my example, http://www.javacodegeeks.com/2010/09/android-text-to-speech-application.html我用这个作为我的例子, http://www.javacodegeeks.com/2010/09/android-text-to-speech-application.html

Please see line 38, says tts.speak(text, TextToSpeech.QUEUE_ADD, null);请看第 38 行,说 tts.speak(text, TextToSpeech.QUEUE_ADD, null);

So, if I have changed the code like this...所以,如果我像这样更改代码......

public class TTA extends Activity implements OnInitListener {

... ... ... ...

 public void MYCall()
 {
 tts.speak(text, TextToSpeech.QUEUE_ADD, null);
 }

... ... ...
}

and then call this my call from another activity, like this,然后把这个称为我从另一个活动中调用的,就像这样,

TTA tta = new TTA();
tta.MYCall();

Shouldn't it work?它不应该工作吗? It doesnt, however when MYCall() is called from within the TTA class it works.它不会,但是当从 TTA class 中调用 MYCall() 时,它会起作用。

Thank you for your help.谢谢您的帮助。

It's hard to tell what's going on, as you haven't provided much code to examine.很难说出发生了什么,因为您没有提供太多代码来检查。

Are you doing set-up for the text-to-speech object in Activity lifecycle methods?您是否正在为 Activity 生命周期方法中的文本转语音 object 进行设置? Those will not get called if you simply instantiate the Activity using new TTA() , so most likely your Text-To-Speech object isn't yet correctly initialized.如果您只是使用new TTA()实例化 Activity,则不会调用这些方法,因此很可能您的文本转语音 object 尚未正确初始化。

However: I would suggest re-arranging your code so that Text-To-Speech related methods are not coupled with a particular Activity, since you'll be using it in multiple places.但是:我建议重新安排您的代码,以便与文本到语音相关的方法不与特定活动耦合,因为您将在多个地方使用它。

You cannot call speak() or tta.MYCall() until onInit() is called.在调用 onInit() 之前,您不能调用speak()tta.MYCall() onInit()

Therefore, running your two lines of code is not likely to work all the time.因此,运行您的两行代码不太可能一直有效。

You need something like this or re-arrange your code:您需要这样的东西或重新安排您的代码:

TTA tta = new TTA();
while (!tta.isInitialized())
{
  try
  {
  Thread.sleep(100);
  }
  catch (InterruptedException e)
  {}
}
tta.MYCall();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM