【问题标题】:Trouble starting a PhoneStateListener from an ON_BOOT_COMPLETED Broadcast Receiver从 ON_BOOT_COMPLETED 广播接收器启动 PhoneStateListener 时遇到问题
【发布时间】:2011-04-16 04:05:07
【问题描述】:

我正在尝试在手机重新启动后重新启动 PhoneStateListener(如果我的 isRunning SharedPref 为真......即监听器在重新启动之前正在运行)

这是我的代码...

Eclipse给我报错就行了:final TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);

它说 getSystemService(String) 没有定义。有谁知道为什么?相同的基本代码在我的主应用程序活动中运行良好。

public class MyReceiver extends BroadcastReceiver {
    SharedPreferences mPrefs;

    String srvcName = Context.TELEPHONY_SERVICE;
    final TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName); 

    @Override
    public void onReceive(Context context, Intent intent) {


        mPrefs = context.getSharedPreferences("myAppPrefs", 0); 
        if(getRunning()){
             telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
        }

      }

【问题讨论】:

  • 当时的logcat是怎么说的?另外,您可以尝试在 onRecieve 方法中移动 getSystemService 调用
  • 没有logcat,它不会编译。此外,将 getSystemService 调用移至 onReceive 也无济于事...... Eclipse 中出现相同的错误消息。

标签: android


【解决方案1】:

首先,它不会编译,因为BroadcastReceiver 不是Context

其次,清单注册的BroadcastReceiver 无法注册侦听器。 BroadcastReceiver 对象及其整个过程可能会在 onReceive() 完成几毫秒后消失。

请收听ACTION_PHONE_STATE_CHANGED 广播,它为您提供与PhoneStateListener 相同的信息。另外,您无需在启动时获得控制权,这样可以节省您的权限并加快用户手机的重启速度。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多