如何使另一个 Android 类文件中的方法在电话铃声响起时运行?
我的情况是,我想调用一个特定的方法,从扩展 BroadcastReceiver 类的 ClassB 内部从 ClassA 调用。我了解如何从另一个类文件等内部执行此操作以及如何设置 BroadcastReceiver,或者我是这么想的。
下面是扩展 BroadcastReceiver 的类文件。 public class WatchPhone extends BroadcastReceiver {
private ClassA classA;
@Override
public void onReceive(Context context, Intent BackToMain) {
// TODO Auto-generated method stub
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
int state = telephony.getCallState();
switch(state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.d("TestServiceReceiver", "IDLE");
classA.IwantToDoThis();
break;
}
}
如果我手动请求它,我尝试调用的方法在应用程序中效果很好。 在我的 AndroidManifest.xml 中,我
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
在底部的关闭应用程序标记上方添加了这个和这个。
<receiver android:name=".WatchPhone">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
当电话响起时,应用程序崩溃然后关闭。关于我应该做什么的任何想法。
My situation is that I want to call a particular method to get called from ClassA from inside my ClassB which extends the BroadcastReceiver class. I understand how to do this from inside another class file etc and how to setup the BroadcastReceiver, or so I thought.
Below is the class file that extends the BroadcastReceiver.
public class WatchPhone extends BroadcastReceiver {
private ClassA classA;
@Override
public void onReceive(Context context, Intent BackToMain) {
// TODO Auto-generated method stub
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
int state = telephony.getCallState();
switch(state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.d("TestServiceReceiver", "IDLE");
classA.IwantToDoThis();
break;
}
}
The method that I am trying to call does work great in the application if I manually request it.
In my AndroidManifest.xml I added this
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
and this at the bottom just above the closing application tag.
<receiver android:name=".WatchPhone">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
When the phone rings, the application crashes then closes. Any ideas on what I should do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我立即看到一个问题:您声明了 ClassA 的一个实例,但没有实例化它。这意味着 classA = null 并且您在使用它时可能会收到 NullPointerException 。
试试这个:
或者,您可以在 onReceive() 顶部附近实例化它:
I can see one problem immediately: you declared an instance of ClassA but did not instantiate it. That means classA = null and you are probably getting a NullPointerException when you use it.
Try this instead:
Alternately, you can instantiate it near the top of onReceive():