如何检测电话状态变化?

时间:2011-07-23 12:12:15

标签: java android service telephony

我正在编写一个Android应用程序,需要从服务中检测手机状态,然后对其进行操作。特别是当来电导致电话振铃时。

我已经阅读了两者的android文档:

  • android.telephony.TelephonyManager
  • android.telephony.PhoneStateListener

但是在尝试在我的服务类中注册TelephonyManager时出现错误。

TelephonyManager tmanager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

结果我不知道我的PhoneStateListener是否可以工作:

注册:

PhoneStateListener phonestatelistener = new phonestatelistener();
tmanager.listen(phonestatelistener, PhoneStateListener.LISTEN_CALL_STATE);

我的听众:

public class phonestatelistener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            //perform action here
        }
        else {
            //perform something else here
        }
        super.onCallStateChanged(state, incomingNumber);
    }
}

有人可以告诉我当手机状态发生变化时如何收听,以及如何在服务中执行操作,因为我觉得我做错了什么,我只是不知道是什么。

[edit1]继承我的logcat:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate service com.xonos.android.silence.SilenceService: java.lang.NullPointerException
 at android.app.ActivityThread.handleCreateService(ActivityThread.java:1929)
 at android.app.ActivityThread.access$2500(ActivityThread.java:117)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:130)
 at android.app.ActivityThread.main(ActivityThread.java:3683)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:507)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
 at android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
 at com.xonos.android.silence.SilenceService.<init>(SilenceService.java:23)
 at java.lang.Class.newInstanceImpl(Native Method)
 at java.lang.Class.newInstance(Class.java:1409)
 at android.app.ActivityThread.handleCreateService(ActivityThread.java:1926)
 ... 10 more

由于

0 个答案:

没有答案